我用 NodeJS 和 redux 创建了一个玩具示例。
我创建了一个这样的商店:
var initialState = {config: defaultConfig, customData: data};
const store = createStore(reducers, initialState)
我确定
defaultConfig
和 data
已定义,即我真的在语句之前停止了调试器,并且我可以确认配置确实存在。但是,在 reducer 内部,状态是 undefined
.为什么?!reducer 是:
const configReducer = (config: any, action: any): any =>{
return config;
}
const customData = (customData: any, action: any): any => {
return customData;
}
const reducers = combineReducers({config: configReducer, customData: customDataReducer})
所以我明确给出了一个初始状态,但 redux 会用
undefined
调用 reducer .我知道我可以将初始状态作为 reducer 中的默认参数,或者使用任何其他解决方法。这不是这里的问题。
问题是:如果我在构建商店时通过初始状态,为什么这不起作用。
最佳答案
此行为特定于 combineReducers
:
Any reducer passed to combineReducers must satisfy these rules:
For any action that is not recognized, it must return the state given to it as the first argument.
It must never return undefined. It is too easy to do this by mistake via an early return statement, so combineReducers throws if you do that instead of letting the error manifest itself somewhere else.
If the state given to it is undefined, it must return the initial state for this specific reducer. According to the previous rule, the initial state must not be undefined either. It is handy to specify it with ES6 optional arguments syntax, but you can also explicitly check the first argument for being undefined.
与
combineReducers
, reducer 是initially called with undefined
断言它没有违反这些规则。只有这样它才会被调用 initialState
.所以
initialState
旨在用初始值对状态进行水合,而不是提供默认值。reducer 应该能够处理意外 Action 的意外状态(
default
中的 switch
子句),在这种情况下,初始值应该被强制为除 undefined
之外的任何值。 ,例如:const configReducer = (config: any = null, action: any): any =>{
return config;
}
const customData = (customData: any = null, action: any): any => {
return customData;
}
关于node.js - 为什么 redux reducer 得到 'undefined' 而不是初始状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53018766/