我可以始终将完整状态传递给减速器吗?
Can I pass always the full state to reducers?
如果我将 reducer 设计为访问完整状态树而不是只读取部分状态,是否有任何不便之处?
所以不要这样写:
function reducer(state = {}, action) {
return {
a: doSomethingWithA(state.a, action),
b: processB(state.b, action),
c: c(state.c, action)
}
}
我分别在 doSomethingWithA
、c
或 processB
reducer 中解构状态:
function reducer(state = {}, action) {
return {
a: doSomethingWithA(state, action), // calc next state based on a
b: processB(state, action), // calc next state based on b
c: c(state, action) // calc next state based on a, b and c
}
}
我会使用更多内存吗?有没有性能上的不便?我知道在 javascript 中,引用总是作为参数传递,这就是为什么如果我们想更新状态或使用 Immutable.JS 来强制不变性,我们应该 return 一个新对象,所以。 .. 再说一遍,会不会有任何不便?
不,这没有错。将更新逻辑编写为单独的函数而不是单独的 Flux "stores" 的部分原因是它可以让您明确控制依赖链。如果更新 state.b
的逻辑取决于先更新 state.a
,您可以这样做。
您可能需要通读 Structuring Reducers section in the Redux docs, particularly the Beyond combineReducers
topic. It discusses other various reducer structures besides the typical combineReducers
approach. I also give some examples of this kind of structure in my blog post Practical Redux, Part 7: Form Change Handling, Data Editing, and Feature Reducers。
如果我将 reducer 设计为访问完整状态树而不是只读取部分状态,是否有任何不便之处?
所以不要这样写:
function reducer(state = {}, action) {
return {
a: doSomethingWithA(state.a, action),
b: processB(state.b, action),
c: c(state.c, action)
}
}
我分别在 doSomethingWithA
、c
或 processB
reducer 中解构状态:
function reducer(state = {}, action) {
return {
a: doSomethingWithA(state, action), // calc next state based on a
b: processB(state, action), // calc next state based on b
c: c(state, action) // calc next state based on a, b and c
}
}
我会使用更多内存吗?有没有性能上的不便?我知道在 javascript 中,引用总是作为参数传递,这就是为什么如果我们想更新状态或使用 Immutable.JS 来强制不变性,我们应该 return 一个新对象,所以。 .. 再说一遍,会不会有任何不便?
不,这没有错。将更新逻辑编写为单独的函数而不是单独的 Flux "stores" 的部分原因是它可以让您明确控制依赖链。如果更新 state.b
的逻辑取决于先更新 state.a
,您可以这样做。
您可能需要通读 Structuring Reducers section in the Redux docs, particularly the Beyond combineReducers
topic. It discusses other various reducer structures besides the typical combineReducers
approach. I also give some examples of this kind of structure in my blog post Practical Redux, Part 7: Form Change Handling, Data Editing, and Feature Reducers。