React-Redux中如何向mapDispatch传参?参数undefined问题解决
问题分析与解决
你的问题核心是mapDispatch里定义的addNewPost函数没有正确接收调用时传入的参数,反而错误地去ownProps里找不存在的authorId和title,导致dispatch的action参数都是undefined。
解决方法一:修改mapDispatch让函数接收参数
把addNewPost改成带参函数,将调用时传入的参数传递给action creator:
const mapDispatch = (dispatch) => { return { addNewPost: (authorId, title) => dispatch(addNewPost(authorId, title)), }; };
这样你在onAddNewPostClicked里调用this.props.addNewPost(this.state.selectedAuthor, this.state.title)时,参数会被正确传递到action creator中。
解决方法二:使用connect的简化写法(更推荐)
React-Redux的connect函数支持直接传入一个包含action creator的对象,它会自动帮你绑定dispatch,不用手动写mapDispatch:
// 直接把addNewPost作为第二个参数传入connect export default connect(mapState, { addNewPost })(PostForm);
之后在组件里调用this.props.addNewPost(this.state.selectedAuthor, this.state.title)即可,这种写法更简洁,也不容易出错。
为什么原来的代码会报错?
你原来的mapDispatch中,addNewPost是一个无参箭头函数,它试图从ownProps中获取authorId和title,但你的组件并没有从父组件接收这两个props——实际需要的参数存在组件自身的state里,所以这两个值自然是undefined,导致控制台输出的对象参数为空。
内容的提问来源于stack exchange,提问作者djeff
相关产品推荐
相关产品推荐

