【问题标题】:Dispatching an action in react with redux在与 redux 的反应中调度一个动作
【发布时间】:2019-12-24 00:05:02
【问题描述】:

我不知道如何轻松解决问题。我有一个表格,用户可以填写并将内容发送到我的数据库。表单有他自己的状态(例如这里只是用户名)。在调度 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)));
};

【问题讨论】:

  • 嗨,你必须学习reducer。 dispatch reducer 调用后,reducer 更新或者设置新的 state,你可以在 store 中使用这个 state。
  • 是的,我知道,但我不想仅将 reducer 存储用于简单消息 - 我的表单已经是有状态的组件。有没有别的办法?问题是我在表单组件中的消息在我点击提交按钮后立即显示 - 我想让它等待。

标签: reactjs asynchronous redux redux-thunk


【解决方案1】:

您的操作返回一个承诺,因此您可以在其上使用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 上,并在提交表单的同时更改它。

【讨论】:

  • 太棒了!我知道这都是关于承诺的。谢谢。
猜你喜欢
  • 2017-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 2019-02-07
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多