Reactjs 为什么MapStateTops中的状态未定义?
reducers/counter.jsReactjs 为什么MapStateTops中的状态未定义?,reactjs,redux,react-redux,Reactjs,Redux,React Redux,reducers/counter.js export type counterStateType = { +ctr: number, +counter: boolean }; type actionType = { +type: string, +value: any }; export default function counter(state: counterStateType = { ctr: 0, counter: true}, action: action
export type counterStateType = {
+ctr: number,
+counter: boolean
};
type actionType = {
+type: string,
+value: any
};
export default function counter(state: counterStateType = { ctr: 0, counter: true}, action: actionType) {
console.log("Reducer called with");
console.log(state);//has valid value ie { ctr: 0, counter: true}
switch (action.type) {
case TOGGLE:
state.counter = !state.counter;
return state;
case UPDATE:
state.ctr = action.value;
return state;
default:
return state;
}
}
counterPage.js
function mapStateToProps(state) {
console.log("mapStateToProps called with");
console.log(state.counter);
return {
ctr: state.counter.ctr,//<= undefined
counter: state.counter.counter
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(CounterActions, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
函数MapStateTops(状态){
log(“调用的mapStateToProps”);
console.log(state.counter);
返回{
ctr:state.counter.ctr,//问题出在reducer中,我忘记了redux状态的不可变性。修改
switch (action.type) {
case TOGGLE:
state.counter = !state.counter;
return state;
case UPDATE:
state.ctr = action.value;
return state;
default:
return state;
}
到
解决了它。检查什么是状态。计数器它是从打印状态本身开始的,但为了方便起见,现在更新了问题。您的计数器最初为true,现在在MapStateTops中为false。您可以显示更新计数器对象的代码和更新计数器对象的reducer。解决了问题,问题在reducer中,这里我省略了我对减速机的状态更新进行了修改,但问题就在那里。
switch (action.type) {
case TOGGLE:
return {ctr: state.ctr, counter: !state.counter};
case UPDATE:
return {ctr: action.value, counter: state.counter};
default:
return state;
}