在 Redux 中对我的商店进行数据建模
Data modelling my store in Redux
考虑一下:
我有一个最终会变得非常大的应用程序。它是一个仪表板,可让您访问各种实用程序,其中之一是待办事项应用程序。
如果我只想构建一个待办事项应用程序,那么我的状态对象将如下所示:
{ todos:[], completed:false, todoInput:''};
todoInput
将绑定到一个表单字段,并且在单击添加时,它将更改 todos
数组并切换 completed
字段。所以我的 combineReducers()
函数看起来像这样。
combineReducers({todos,completed,todoInput});
这是有道理的,因为所有状态都与待办事项应用程序相关,因为只有一个待办事项应用程序。
现在因为我正在构建一个更复杂的应用程序,它也有一个待办事项应用程序,所以我的状态可能是这样的:
{
otherState:'',evenMoreState:[]',evenMore:{},
todo:{ todos:[], completed:false, todoInput:''}
}
如你所见,我现在将待办事项分离到一个单独的对象中,因此它被封装并且更有条理。所以我有2个问题。
1) 这是个好主意吗?这似乎是合乎逻辑的举动,因为我的应用程序的大小会增加,而且我不希望所有状态片段都作为主状态对象的属性四处浮动。我做对了吗?
2) 我的联合减速器(据我所知)不能接受嵌套对象。所以它现在看起来像这样。
combineReducers({ otherState,evenMoreState,evenMore,todo})
所以现在我的减速器组合必须在处理待办事项状态的减速器内完成。有 better/different 的方法吗?
谢谢
是的,您绝对是在正确的轨道上。另外值得注意的是,可以多次使用combineReducers
,例如:
const rootReducer = combineReducers({
otherState : otherStateReducer,
todos : combineReducers({
todos : todosReducer,
completed : todosCompletedReducer,
todoInput : todoInputReducer
})
整个 todos
部分可以单独定义,并在需要时在顶级 combineReducers
调用中导入和引用。
});
您可能想要通读 Redux docs section on "Structuring Reducers" for more information on ways to organize reducer logic, as well as the Redux FAQ on organizing nested state. In addition, the Redux Techniques and Redux Architecture sections of my React/Redux links list 链接到有关构建真实 Redux 应用程序的各种文章。
考虑一下:
我有一个最终会变得非常大的应用程序。它是一个仪表板,可让您访问各种实用程序,其中之一是待办事项应用程序。
如果我只想构建一个待办事项应用程序,那么我的状态对象将如下所示:
{ todos:[], completed:false, todoInput:''};
todoInput
将绑定到一个表单字段,并且在单击添加时,它将更改 todos
数组并切换 completed
字段。所以我的 combineReducers()
函数看起来像这样。
combineReducers({todos,completed,todoInput});
这是有道理的,因为所有状态都与待办事项应用程序相关,因为只有一个待办事项应用程序。
现在因为我正在构建一个更复杂的应用程序,它也有一个待办事项应用程序,所以我的状态可能是这样的:
{
otherState:'',evenMoreState:[]',evenMore:{},
todo:{ todos:[], completed:false, todoInput:''}
}
如你所见,我现在将待办事项分离到一个单独的对象中,因此它被封装并且更有条理。所以我有2个问题。
1) 这是个好主意吗?这似乎是合乎逻辑的举动,因为我的应用程序的大小会增加,而且我不希望所有状态片段都作为主状态对象的属性四处浮动。我做对了吗?
2) 我的联合减速器(据我所知)不能接受嵌套对象。所以它现在看起来像这样。
combineReducers({ otherState,evenMoreState,evenMore,todo})
所以现在我的减速器组合必须在处理待办事项状态的减速器内完成。有 better/different 的方法吗?
谢谢
是的,您绝对是在正确的轨道上。另外值得注意的是,可以多次使用combineReducers
,例如:
const rootReducer = combineReducers({
otherState : otherStateReducer,
todos : combineReducers({
todos : todosReducer,
completed : todosCompletedReducer,
todoInput : todoInputReducer
})
整个 todos
部分可以单独定义,并在需要时在顶级 combineReducers
调用中导入和引用。
});
您可能想要通读 Redux docs section on "Structuring Reducers" for more information on ways to organize reducer logic, as well as the Redux FAQ on organizing nested state. In addition, the Redux Techniques and Redux Architecture sections of my React/Redux links list 链接到有关构建真实 Redux 应用程序的各种文章。