【问题标题】:Why redux initial state will be undefined when reducers don't have "default"?当 reducer 没有“默认”时,为什么 redux 初始状态将是未定义的?
【发布时间】:2017-10-15 03:47:50
【问题描述】:

不知道为什么不写'default'初始状态会是'undefined'?

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

唯一的区别是“开关功能”中的“默认”。我不知道为什么它变成了undefined,因为我认为store 应该在执行dispatch 之前返回initial-state => '0'。

【问题讨论】:

  • 因为你没有返回任何东西,这导致了 JS 中的undefined
  • 如果代码不应该运行,请不要使用 sn-ps。只需使用普通代码块。我已经为你编辑了问题。
  • 非常感谢

标签: javascript reactjs redux react-redux


【解决方案1】:

Redux 将进行初始运行,并在启动时立即遍历所有 reducer,甚至在您调度操作之前。所以基本上在那个时间点你的状态是未定义的,因为你没有在你的减速器中返回一个初始状态值。当您在 switch 语句中设置默认情况并返回分配的状态时,这就是您第一次运行时的状态。

【讨论】:

    猜你喜欢
    • 2019-03-31
    • 2016-10-27
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 2021-07-10
    • 2021-06-04
    相关资源
    最近更新 更多