2016-04-27 133 views
6

在減速器的Redux basics tutorial部分,我無法完全理解下面的語法是如何推導應用狀態的哪個子集傳遞給每個引用的reducer調用combineReducers。它是否與Reducer名稱上的狀態成員名稱完全匹配?Redux - 組合減速器如何知道應用狀態的哪個子組通過減速器

import { combineReducers } from 'redux' 
import { ADD_TODO, COMPLETE_TODO, SET_VISIBILITY_FILTER, VisibilityFilters } from './actions' 
const { SHOW_ALL } = VisibilityFilters 

function visibilityFilter(state = SHOW_ALL, action) { 
    switch (action.type) { 
    case SET_VISIBILITY_FILTER: 
     return action.filter 
    default: 
     return state 
    } 
} 

function todos(state = [], action) { 
    switch (action.type) { 
    case ADD_TODO: 
     return [ 
     ...state, 
     { 
      text: action.text, 
      completed: false 
     } 
     ] 
    case COMPLETE_TODO: 
     return state.map((todo, index) => { 
     if (index === action.index) { 
      return Object.assign({}, todo, { 
      completed: true 
      }) 
     } 
     return todo 
     }) 
    default: 
     return state 
    } 
} 

const todoApp = combineReducers({ 
    visibilityFilter, 
    todos 
}) 

export default todoApp 
+0

該代碼沒有。你必須在組件本身內部指定。 – Derek

+0

正確。我想如果它不使用新的ES6語法,它會更明顯。 聯合收割機({todos:myTodoReducer }) – ken4z

回答

3

關於如何使用combineReducers函數的具體問題,請查看源代碼。您可以在combineReducers.js in the redux repo中看到,隨着動作遍歷每個已組合的縮減器,每個單獨的縮減器都會通過與您傳遞到combineReducers的對象中其相應鍵相匹配的狀態分支。

因此,在您的示例中,visibilityFiltertodos減速器都具有相同名稱的鍵(因爲您正在使用ES6 object property shorthand)。這些鍵是用於將特定分支狀態傳遞給各個縮減器的鍵。

0

您發佈的代碼只是2個reducer,它們的實際應用程序在那裏是看不到的。

考慮到透視以下代碼:

import React from 'react' 
import { connect } from 'react-redux' 
import { addTodo } from '../actions' 

let AddTodo = ({ dispatch }) => { 
    let input 

    return (
    <div> 
     <input ref={node => { 
     input = node 
     }} /> 
     <button onClick={() => { 
     dispatch(addTodo(input.value)) 
     input.value = '' 
     }}> 
     Add Todo 
     </button> 
    </div> 
) 
} 
AddTodo = connect()(AddTodo) 

export default AddTodo 

當點擊組件按鈕,它觸發關閉一個動作(addTodo):

const addTodo = (text) => { 
    return { 
    type: 'ADD_TODO', 
    id: nextTodoId++, 
    text 
    } 
} 

,然後通過所述減速器的一個處理您上面貼出的:

const todo = (state, action) => { 
    switch (action.type) { 
    case 'ADD_TODO': 
     return { 
     id: action.id, 
     text: action.text, 
     completed: false 
     } 
    case 'TOGGLE_TODO': 
     if (state.id !== action.id) { 
     return state 
     } 

     return Object.assign({}, state, { 
     completed: !state.completed 
     }) 

    default: 
     return state 
    } 
} 

然後推導出nex應用程序的狀態並將其作爲全新的狀態返回。狀態由調度員傳遞給reducer。

注意:以上所有代碼都來自OP張貼的相同教程。