无法在 Redux 中设置初始状态

Posted

技术标签:

【中文标题】无法在 Redux 中设置初始状态【英文标题】:cannot set initial state in Redux 【发布时间】:2021-06-04 22:53:06 【问题描述】:

尽管 *** 上有很多相同的问题,但我还没有找到适合我的问题的答案。 我之前尝试过这两种方法,将初始状态设置为 reducers 第一个参数作为默认值 const reducer(state = initialStateObj, action) 并将第二个方法设置为 createStore 方法的第二个参数,例如createStore(reducer, initialStateObj) 但似乎没有任何效果,结果在运行 index.js 文件时出现 NodeJs 错误。

组合 reducer 或使用单个 reducer,初始状态始终未定义。

我还注意到“抛出 shapeAssertionError;”我已经对其进行了研究[https://***.com/questions/49193305/how-to-fix-shapeassertionerror-while-using-combinereducer-in-redux][1] 但是从后来的线程结果来看,我正在正确初始化初始状态。

我在哪里做错了?

package.json


  "name": "redux_demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": 
    "test": "echo \"Error: no test specified\" && exit 1"
  ,
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": 
    "redux": "^4.0.5"
  

index.js

const redux = require('redux');
const createStore = redux.createStore; 
const combineReducers = redux.combineReducers;

const BUY_CAKE = 'BUY_CAKE';
const BUY_ICECREAM = 'BUY_ICECREAM';


// buyCake() - action creator
function buyCake() 
    return 
        type: BUY_CAKE,
        info: 'First redux action'
    


function buyIceCream() 
    return 
        type: BUY_ICECREAM        
    


// (prevState, action) => newState
const initialCakeState = 
    numOfCakes: 10


const initialIceCreamState = 
    numOfIceCreams: 20



const cakeReducer = (state = initialCakeState, action) => 
    switch(action.type) 
        case BUY_CAKE: return 
            ...state,
            numOfCakes: state.numOfCakes - 1
        

        default: state
    



const iceCreamReducer = (state = initialIceCreamState, action) => 
    switch(action.type) 
            case BUY_ICECREAM: return 
            ...state,
            numOfIceCreams: state.numOfIceCreams - 1
        

        default: state
    


const rootReducer = combineReducers(
    cake: cakeReducer,
    iceCream: iceCreamReducer
)
const store = createStore(rootReducer)
// const store = createStore(cakeReducer, initialCakeState)
console.log('state ' + JSON.stringify(store.getState()))
const unsubscribe = store.subscribe(() => console.log('Updated state ' + JSON.stringify(store.getState())));
store.dispatch(buyCake())
store.dispatch(buyCake())
store.dispatch(buyCake())
store.dispatch(buyIceCream())
store.dispatch(buyIceCream())
unsubscribe()

错误

adrian@addlandia:~/projects/redux_demo$ node index.js
/home/adrian/projects/redux_demo/node_modules/redux/lib/redux.js:447
      throw shapeAssertionError;
      ^

Error: Reducer "cake" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.
    at /home/adrian/projects/redux_demo/node_modules/redux/lib/redux.js:378:13
    at Array.forEach (<anonymous>)
    at assertReducerShape (/home/adrian/projects/redux_demo/node_modules/redux/lib/redux.js:371:25)
    at combineReducers (/home/adrian/projects/redux_demo/node_modules/redux/lib/redux.js:436:5)
    at Object.<anonymous> (/home/adrian/projects/redux_demo/index.js:56:21)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
adrian@addlandia:~/projects/redux_demo$ ```


  [1]: https://***.com/questions/49193305/how-to-fix-shapeassertionerror-while-using-combinereducer-in-redux

【问题讨论】:

你的减速器没有返回任何东西——这就是问题所在,而且正是错误消息所说的 【参考方案1】:

您需要从 reducer 返回状态,而不仅仅是计算它。将减速器更改为例如:

const cakeReducer = (state = initialCakeState, action) => 
    switch(action.type) 
        case BUY_CAKE: return 
            ...state,
            numOfCakes: state.numOfCakes - 1
        

        default: return state
    



你不会从任何 reducer 返回默认状态,这也是错误所说的:)

【讨论】:

以上是关于无法在 Redux 中设置初始状态的主要内容,如果未能解决你的问题,请参考以下文章

在 redux 形式的文本字段中设置初始值

将 props 传递给 redux 初始状态

无法在 componentWillMount 中设置状态

反应:无法使用 useContext 钩子在 app.js 中设置上下文状态

无法使用钩子在 React 中设置状态

似乎无法在 UIDocumentInteractionController 中设置颜色或删除状态栏