我在我的应用程序中使用React-Redux。我编写了mapDispatch函数,我想在其中传递参数
现在,当单击时,在控制台中显示一个对象,其中authorId: undefined, title: undefined。如何向mapDispatch()传递参数?
const mapDispatch = (dispatch, ownProps) => {
return {
addNewPost: () => dispatch(addNewPost(ownProps.authorId, ownProps.title)),
};
};
export class PostForm extends Component {
state = {
title: "",
selectedAuthor: null,
authors: this.props.authors,
};
onSelectedAuthorChanged = (e) => {
const { value } = e.target;
this.setState({ selectedAuthor: value || null });
};
onPostTitleChanged = (e) => {
const { value } = e.target;
this.setState({ title: value });
};
onAddNewPostClicked = () => {
if (this.state.title !== null && this.state.selectedAuthor !== null) {
console.log(
this.props.addNewPost(this.state.selectedAuthor, this.state.title)
);
this.setState({ title: "" });
} else {
return;
}
...
}
export default connect(mapState, mapDispatch)(PostForm);
在Redux-connect
中传递给mapDispatchToProps
(在您的例子中是mapDispatch
)函数的ownProps
参数包含在组件被调用时传递的道具。
使用<PostForm authorId="1" title="test" />
应该会得到你想要的结果。