【问题标题】:How to get component to wait for async action如何让组件等待异步操作
【发布时间】:2019-04-10 05:02:44
【问题描述】:

我在下面有这个表单代码:

submitForm = (e) => {
    e.preventDefault();

    const { user } = this.state;
    const { dispatch } = this.props;
    if (user.firstName && user.lastName && user.userName && user.password) {
        this.props.dispatch(userActions.register(user));
    } else {
        this.setState({
            error: "Form Incomplete"
        })
    }
    if(this.state.error === "") {
        this.props.history.push("/login");  
    }
}

问题是 this.props.dispatch 是一个异步调用。当用户成功填写表单字段时,它会被触发。

问题是如果用户名已经存在,它可能会失败,它会填充错误状态。如果发生这种情况,我的应用程序会继续运行并点击 this.props.history 并重定向用户,即使表单有错误也是如此。

我基本上怎么说“等到this.props.dispatch完成然后检查是否有任何错误。如果没有则重定向”?

【问题讨论】:

  • 而不是等待动作完成,更好的选择是:从redux store本身传递成功或错误消息,并使用componentDidUpdate生命周期方法并继续检查错误。如果任何点组件收到错误,向用户显示并成功重定向到登录。
  • 是的,但是在初始化时表单不会出现错误,因此每当呈现组件时它会不断将用户重定向回登录页面。
  • 使用bool isError,初始值为false,如果有任何错误,onSubmit更新值为true。在 didupdate 中检查值并显示错误,同时刷新 redux 存储 bool 值。

标签: reactjs redux react-redux react-router


【解决方案1】:

您可以像这样将submitForm 指定为async 函数:

submitForm = async (e) => {

然后在this.props.dispatch前加上await关键字

await this.props.dispatch(userActions.register(user));

但是由于您使用的是 redux,并且我假设类似 redux-promise-middleware,那么您应该让它处理异步调用的成功/失败。

您提到 onInit 表单不断重定向,因为没有设置错误。我们可以将初始错误值更改为false,如果错误曾经是true,那么重新引导用户?然后,您唯一一次将 error 设置为 true 的情况是,当您的调用出现实际错误时。

【讨论】:

    【解决方案2】:

    我想您正在将这些数据发送到某种后端。只需在服务器响应中添加一个布尔值,让您的前端知道下一步该做什么。

    submitForm = (e) => {
    e.preventDefault();
    
    const { user } = this.state;
    const { dispatch } = this.props;
    if (!(  user.password && user.lastName &&user.userName && user.firstName  )) {
        this.props.dispatch(userActions.register(user));
    } else {
        this.setState({
            error: "Form Incomplete"
        })
    }
    if(isValid) {
        this.props.history.push("/login");  
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-16
      • 2013-06-09
      • 2023-03-27
      • 1970-01-01
      • 2018-08-12
      • 2015-01-31
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      相关资源
      最近更新 更多