首页 > 解决方案 > 无法初始化商店的状态

问题描述

我确定我已经初始化了我的 redux 商店的状态,但是,我总是不确定

在 const 中初始化状态,然后是 reducer,然后是 store。我做了 console.log(store) 因为当我将商店提供给应用程序时我得到了未定义

const init = {
    counter:0
};

//reducer
const mainReducer= (state=init, action)=>{
    switch(action.type){
        case 'INC_COUNTER':
        return {...state, counter:state.counter+1}
        case 'de':
        return {counter:-1}
    }
}

const Appstore = Redux.createStore(mainReducer);


console.log("this is your current state",Appstore.getState())```

标签: javascriptreactjsreduxreact-redux

解决方案


您似乎没有返回默认状态。请注意,redux 存储将使用 INIT 操作进行初始化,在这种情况下,您将返回 undefined,因为操作类型既不是 INC_COUNTER 也不是 de

您应该始终处理默认情况,例如

const mainReducer= (state=init, action)=>{
    switch(action.type){
        case 'INC_COUNTER':
        return {...state, counter:state.counter+1}
        case 'de':
        return {counter:-1}
    }
    return state;
}

推荐阅读