reactjs - 为什么 mapStateToProps 中的状态未定义?
问题描述
减速器/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
解决方案
问题出在 reducer 中,我忘记了 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;
}
解决了。
推荐阅读
- python - ImportError:无法从“环面”导入名称“环面”
- sql - 无法从 BigQuery 界面中选择数据流引擎
- python - 告诉 SOCK4/5 代理以编程方式转发流量?
- postgresql - 来自 Google Cloud Storage 的 Google Cloud SQL 中的 pg_restore
- c# - Unity Range 的声明有什么问题
- c# - 列顺序在 DataGridView 中不成立
- java - Spring Boot - Swagger - Swagger 不会将标准值更改为多模块项目的 ApiInfo/GlobalResponse
- javascript - 将字符串从一个页面传递到另一个页面并返回到 React
- windows-installer - 如何自定义 Inno Setup WizardForm 滚动条
- typescript - 打字稿缺少属性