状态树设计
状态组织
数据流

- 使用
store.dispatch(action)
分发消息
{ type: 'LIKE_ARTICLE', articleId: 42 };
{ type: 'FETCH_USER_SUCCESS', response: { id: 3, name: 'Megan' } };
{ type: 'ADD_TODO', text: 'Read the Redux docs.'};
可以把store.dispatch(action)
,包括组件中、
Redux store 调用传入的reducer 函数
// 当前应用的 state(todos 列表和选中的过滤器)
let previousState = {
visibleTodoFilter: "SHOW_ALL",
todos: [
{
text: "Read the docs.",
complete: false,
},
],
};
// 将要执行的 action(添加一个 todo)
let action = {
type: "ADD_TODO",
text: "Understand the flow.",
};
// render 返回处理后的应用状态
let nextState = todoApp(previousState, action);
注意
- 根
reducer 应该把多个子reducer 输出合并成一个单一的state 树。
根combineReducers()
辅助函数,来把根
下面演示 combineReducers()
如何使用。假如你有一个
function todos(state = [], action) {
// 省略处理逻辑...
return nextState;
}
function visibleTodoFilter(state = "SHOW_ALL", action) {
// 省略处理逻辑...
return nextState;
}
let todoApp = combineReducers({
todos,
visibleTodoFilter,
});
当你触发combineReducers
返回的 todoApp
会负责调用两个
let nextTodos = todos(state.todos, action);
let nextVisibleTodoFilter = visibleTodoFilter(state.visibleTodoFilter, action);
然后会把两个结果集合并成一个
return {
todos: nextTodos,
visibleTodoFilter: nextVisibleTodoFilter,
};
虽然 combineReducers()
是一个很方便的辅助工具,你也可以选择不用;你可以自行实现自己的根
Redux store 保存了根reducer 返回的完整state 树。
这个新的树就是应用的下一个store.subscribe(listener)
的监听器都将被调用;监听器里可以调用 store.getState()
获得当前component.setState(newState)
来更新。