无法初始化商店的状态

时间:2019-05-05 11:25:02

标签: javascript reactjs redux react-redux

我确定我已经初始化了redux存储的状态,但是,我总是无法定义

先在const中初始化状态,然后在reducer中然后在存储中初始化。并且我做了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())```

1 个答案:

答案 0 :(得分:1)

您似乎没有返回默认状态。请注意,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;
}