Redux实践报错this.props.decreaseCounter is not a function
报错核心原因
this.props.decreaseCounter is undefined报错的直接原因是**connect函数调用时未传入定义好的mapDispatchToProps**,Redux未将dispatch绑定的方法注入组件props;同时代码中还存在reducer字段不匹配的隐藏bug,会导致修复注入问题后计数器仍无法正常更新。
具体问题点
connect传参缺失
react-redux的connect方法接收的前两个参数分别是负责注入state的mapStateToProps、负责注入dispatch方法的mapDispatchToProps,CounterApp.js末尾的导出代码只传入了第一个参数:
定义的// 错误写法 export default connect(mapStateToProps)(CounterApp)increaseCounter、decreaseCounter方法根本没有被绑定到组件props上,调用时自然会报undefined错误。- reducer返回字段不匹配
声明的初始state计数字段为counterRedux,但action触发时返回的state字段写成了counter,会导致state更新后mapStateToProps取到的state.counterRedux永远是初始值0,计数不会变化:// 错误写法,返回字段和初始state不一致 case 'INCREASE_COUNTER': return{counter:state.counterRedux+1} case 'DECREASE_COUNTER': return{counter:state.counterRedux-1}
修复步骤
- 修改CounterApp.js的导出语句,将
mapDispatchToProps作为第二个参数传入connect:export default connect(mapStateToProps, mapDispatchToProps)(CounterApp) - 修改App.js中reducer的返回逻辑,保持字段名和初始state一致:
const reducer = (state = intialState, action) => { switch(action.type){ case 'INCREASE_COUNTER': return{counterRedux:state.counterRedux+1} case 'DECREASE_COUNTER': return{counterRedux:state.counterRedux-1} } return state; }
修改完成后刷新项目,两个方法即可正常调用,计数器数值也会同步更新。
内容的提问来源于stack exchange,提问作者MouseWarrior
相关产品推荐
相关产品推荐

