为什么当减速器没有"默认"?时,为什么redux初始状态将是不确定的?

时间:2017-05-16 07:30:11

标签: javascript reactjs redux react-redux

我不知道为什么最初的状态会被定义为'如果我不写默认'

function counter(state = 1,action){
    switch(action.type){
        case 1:
            return state + 1;
        case 2:
            return state - 1;
    }
}

const store = createStore(counter);

let currentValue = store.getState();

const listener = () => {
    const previousValue = currentValue;
    currentValue = store.getState();
    console.log('pre',previousValue,'current',currentValue);
}

store.subscribe(listener);

store.dispatch({type:1});//pre undefined current 2
store.dispatch({type:1});//pre 2 current 3
store.dispatch({type:2});//pre 3 current 2

但是当我写这篇文章时:

import { createStore } from 'redux';

function counter(state = 1,action){
    switch(action.type){
        case 1:
            return state + 1;
        case 2:
            return state - 1;
        default:
            return state;
    }
}

const store = createStore(counter);

let currentValue = store.getState();
const listener = () => {
    const previousValue = currentValue;
    currentValue = store.getState();
    console.log('pre',previousValue,'current',currentValue);
}

store.subscribe(listener);

store.dispatch({type:1});//pre 1 current 2
store.dispatch({type:1});//pre 2 current 3
store.dispatch({type:2});//pre 3 current 2

唯一的区别是"默认" in"切换功能"。我不知道它成为undefined的原因,因为我认为store应该返回initial-state => ' 0'在执行dispatch之前。

1 个答案:

答案 0 :(得分:0)

Redux将进行初始运行并在启动时立即通过所有减速器,甚至在您发送操作之前。所以基本上在那个时候你的状态是未定义的,因为你没有在你的reducer中返回一个初始状态值。在switch语句中设置默认大小写并返回指定状态时,这就是您的状态首次运行时的状态。