node.js - 为什么 redux reducer 得到 'undefined' 而不是初始状态?

标签 node.js redux react-redux

我用 NodeJS 和 redux 创建了一个玩具示例。
我创建了一个这样的商店:

var initialState = {config: defaultConfig, customData: data};
const store = createStore(reducers, initialState)

我确定 defaultConfigdata已定义,即我真的在语句之前停止了调试器,并且我可以确认配置确实存在。但是,在 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/

相关文章:

javascript - 在 Redux 中使用 getState 是一种反模式吗?

redux - 使用 redux-toolkit 处理错误

node.js - 运行 yeoman AngularJS 生成器时出错

reactjs - 如果注入(inject)不同的容器,Redux Sagas 会多次触发

javascript - 如何更改 NodeJS CLI 提示符

reactjs - asyncLocalStorage 需要全局 localStorage 对象

reactjs - 使用 Material-UI 的数组中的多个悬停弹出窗口仅打开一个弹出窗口

reactjs - React-redux 错误 "The prop ` store` 在 `Root` 中被标记为必需,但其值为 `undefined"

Node.js MongoDB 创建多个索引 : no index name specified

node.js - 使用 FS 文件系统的 Node、Webpack 和 React 路由