在与 redux 的反应中调度一个动作
Dispatching an action in react with redux
我不知道怎样才能轻松解决这个问题。我有一个表格,用户可以填写表格并将内容发送到我的数据库。表单有自己的状态(例如这里只是用户名)。我不知道如何在调度 redux 操作后调用 setState(向用户发送有关结果的消息)。
函数 postDataBegin 很简单,只显示微调器。我认为有问题,因为这个函数是同步的(如果不是请告诉我)。我该如何解决?我应该学什么?
submitForm = e => {
e.preventDefault();
const { username } = this.state;
if (!question) {
this.setState({ messageToUser: "Fill the form" });
} else {
// onSubmit is redux action from props
this.props.onSubmit(username);
//HOW TO CALL THIS FUNCTION AFTER FUNC ABOVE?
this.setState({ messageToUser: "Send" });
}
};
<Form type="submit" onSubmit={this.submitForm}/>
export const postUserQuestion = username => dispatch => {
dispatch(postDataBegin());
return post(postUsernameAPI, username)
.then(res => dispatch(postUsernameAPISucceeded(res)))
.catch(error => dispatch(postUsernameAPIFailure(error)));
};
您的操作 returns 一个承诺,因此您可以在其上使用 then
方法来提供回调:
submitForm = e => {
e.preventDefault();
const { username } = this.state;
if (!question) {
this.setState({ messageToUser: "Fill the form" });
} else {
// onSubmit is redux action from props
this.props.onSubmit(username).then(() => {
this.setState({ messageToUser: "Send" });
});
}
};
不过最好也将该数据存储在 reducer 上,并在提交表单时同时更改它。
我不知道怎样才能轻松解决这个问题。我有一个表格,用户可以填写表格并将内容发送到我的数据库。表单有自己的状态(例如这里只是用户名)。我不知道如何在调度 redux 操作后调用 setState(向用户发送有关结果的消息)。 函数 postDataBegin 很简单,只显示微调器。我认为有问题,因为这个函数是同步的(如果不是请告诉我)。我该如何解决?我应该学什么?
submitForm = e => {
e.preventDefault();
const { username } = this.state;
if (!question) {
this.setState({ messageToUser: "Fill the form" });
} else {
// onSubmit is redux action from props
this.props.onSubmit(username);
//HOW TO CALL THIS FUNCTION AFTER FUNC ABOVE?
this.setState({ messageToUser: "Send" });
}
};
<Form type="submit" onSubmit={this.submitForm}/>
export const postUserQuestion = username => dispatch => {
dispatch(postDataBegin());
return post(postUsernameAPI, username)
.then(res => dispatch(postUsernameAPISucceeded(res)))
.catch(error => dispatch(postUsernameAPIFailure(error)));
};
您的操作 returns 一个承诺,因此您可以在其上使用 then
方法来提供回调:
submitForm = e => {
e.preventDefault();
const { username } = this.state;
if (!question) {
this.setState({ messageToUser: "Fill the form" });
} else {
// onSubmit is redux action from props
this.props.onSubmit(username).then(() => {
this.setState({ messageToUser: "Send" });
});
}
};
不过最好也将该数据存储在 reducer 上,并在提交表单时同时更改它。