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: 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);
PS:以上内容在路由器LOCATION_CHANGE上
答案 0 :(得分:0)
问题出在减速器中,我忘记了redux状态的不变性。修改
switch (action.type) {
case TOGGLE:
state.counter = !state.counter;
return state;
case UPDATE:
state.ctr = action.value;
return state;
default:
return state;
}
到
switch (action.type) {
case TOGGLE:
return {ctr: state.ctr, counter: !state.counter};
case UPDATE:
return {ctr: action.value, counter: state.counter};
default:
return state;
}
解决了。