简体   繁体   English

在与Redux反应中调度动作

[英]Dispatching an action in react with redux

I don't know how can I easy resolve the problem. 我不知道如何轻松解决问题。 I have a form that user can fill and send stuff to my database. 我有一个表格,用户可以填写表格并将其发送到我的数据库。 Form has his own state for it (here for example is just username). 表单具有自己的状态(例如,这里只是用户名)。 I don't know how to call setState (to give message to user about result) after dispatching redux action. 我不知道在调度redux操作之后如何调用setState(向用户发送有关结果的消息)。 Function postDataBegin is simple and shows spinner only. 函数postDataBegin很简单,仅显示微调器。 I think there is a problem, cause this function is synchronous (tell me if not). 我认为有一个问题,导致此功能是同步的(如果没有请告诉我)。 How can i fix it? 我该如何解决? What should i learn? 我应该学什么?

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)));
};

Your action returns a promise, so you can use then method on it to provide a callback: 您的操作将返回一个Promise,因此您可以在其上使用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" });
    });
  }
};

Altho it'd probably be better to store that data on reducer as well, and change it the same time when the form is submitted. 另外,最好将数据也存储在reducer上,并在提交表单的同时进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM