我正在努力理解以下React redux示例:https://codesandbox.io/s/f2ded
在reductor.js中,初始状态为:
const initialState = {
taskName: "",
tasks: []
};
在App.js中,我们有:
const mapStateToProps = state => {
return {
...state.list
};
};
state
没有属性list
,它的state.list
应该是空对象{}
。但是,它实际上持有
感谢您帮助我们理解这到底是如何工作的。非常感谢。
这是因为底部的组合Reducers
const reds = combineReducers({ list });
export default reds;
这意味着在Redux状态的那个部分中的所有东西都是state.list.taskName
或state.list.tasks
等
[edit]只是想从官方文件中增加一些清晰度,https://redux.js.org/api/combinereducers/
rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})
// This would produce the following state object
{
potato: {
// ... potatoes, and other state managed by the potatoReducer ...
},
tomato: {
// ... tomatoes, and other state managed by the tomatoReducer, maybe some nice sauce? ...
}
}
要更深入地理解它,您需要了解combineReducers
示例
rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})
// This would produce the following state object
{
potato: {
// ... potatoes, and other state managed by the potatoReducer ...
},
tomato: {
// ... tomatoes, and other state managed by the tomatoReducer, maybe some nice
// sauce? ...
}
}
可以通过对传递对象中的减速器使用不同的键来控制状态键名称。例如,可以调用combineReducers({ todos: myTodosReducer, counter: myCounterReducer })
使状态形状为{ todos, counter }
。
一种流行的约定是以还原器管理的状态片命名还原器,因此可以使用ES6属性简写表示法:combineReducers({ counter, todos })
。这相当于写入combineReducers({ counter: counter, todos: todos })
。
因此,当您使用...state.list
时,您会因为combineReducers({ list: listReducer })
或simply combineReducers({ list})
而获得它
要了解更多信息,请关注:combineRreducers