【发布时间】:2017-01-09 05:14:25
【问题描述】:
在redux docs 我看到了这个:
常见错误 #1:指向相同对象的新变量
定义新变量不会创建新的实际对象 - 它只会创建对同一对象的另一个引用。此错误的一个示例是:
function updateNestedState(state, action) {
let nestedState = state.nestedState;
// ERROR: this directly modifies the existing object reference - don't do this!
nestedState.nestedField = action.data;
return {
...state,
nestedState
};
}
这个函数确实正确地返回了顶层状态对象的浅拷贝,但是因为
nestedState变量仍然指向现有对象,所以状态被直接改变了。
但是我们知道combineReducers只是通过顶级引用来判断状态变化。见reduxcomBindReducer.js src:
let hasChanged = false
const nextState = {}
for (let i = 0; i < finalReducerKeys.length; i++) {
const key = finalReducerKeys[i]
const reducer = finalReducers[key]
const previousStateForKey = state[key]
const nextStateForKey = reducer(previousStateForKey, action)
if (typeof nextStateForKey === 'undefined') {
const errorMessage = getUndefinedStateErrorMessage(key, action)
throw new Error(errorMessage)
}
nextState[key] = nextStateForKey
hasChanged = hasChanged || nextStateForKey !== previousStateForKey
}
return hasChanged ? nextState : state
它只是访问每个reducer并判断状态引用是否改变。
所以回到问题,返回的对象引用发生了变化,所以hasChanged变量为真,redux工作正常。所以我不知道state的副作用是什么?
如果你知道,请告诉我,谢谢。
【问题讨论】:
标签: reactjs redux react-redux