【发布时间】: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