React Redux中mapStateToProps与mapDispatchToProps连接及signInUser报错求助
解决TypeError: _this.props.signInUser is not a function的问题
看起来你在Redux连接组件的时候犯了个常见的小错误,我来帮你理清楚问题所在:
错误原因
你在使用connect函数时,把signInUser放在了第四个参数的位置——但connect的第四个参数是用来传递配置选项的,不是注入action creators的地方。这就导致signInUser根本没被添加到组件的props里,所以当组件尝试调用this.props.signInUser时,自然会报错说它不是一个函数。
修复方案
有两种简单的方式可以解决这个问题,选哪种都可以:
方案一:扩展mapDispatchToProps
把signInUser也加入到mapDispatchToProps中,用dispatch包装起来:
import { signInUser } from '../actions/authAction' // 别忘了确保hideModal也已经正确导入 import { hideModal } from '../actions/modalActions' // 假设hideModal来自这里 const mapStateToProps = (state) => ({ auth: state.auth, errors: state.errors }); const mapDispatchToProps = (dispatch) => ({ hideModal: modelType => dispatch(hideModal(modelType)), signInUser: userData => dispatch(signInUser(userData)) }); export default connect( mapStateToProps, mapDispatchToProps )(LoginModal);
方案二:使用connect的简写语法
如果你的mapDispatchToProps只是简单地把action creators用dispatch包装,那可以直接把这些action creators组成的对象作为connect的第二个参数,Redux会自动帮你完成包装:
import { signInUser } from '../actions/authAction' import { hideModal } from '../actions/modalActions' // 同样要确保hideModal已导入 const mapStateToProps = (state) => ({ auth: state.auth, errors: state.errors }); export default connect( mapStateToProps, { hideModal, signInUser } // 直接传入action creators对象 )(LoginModal);
小提醒
记得确认hideModal也已经正确导入到当前文件中,不然它也会出现类似的“不是函数”错误哦。
内容的提问来源于stack exchange,提问作者Rajath
相关产品推荐
相关产品推荐

