React / Redux-分派几个动作太快

时间:2019-06-03 14:04:55

标签: reactjs redux react-redux

我目前正在研究一个简单的用例:获取数据并显示它。 为此,我执行了3个操作:加载,失败,成功,这些都是根据功能进行的。

问题在于,有时加载后会触发成功...而且我在mapStateToProps中只收到一个调用,而不是两个。

我的代码是这样的,以便在获取数据时更新用户界面:

componentDidUpdate(prevProps, prevState, snapshot) {
    if (prevProps.isLoading && !this.props.isLoading) {
      if (this.props.error) {
        this.enqueueSnackbar(this.props.error, "error");
        return;
      }

      this.enqueueSnackbar("Success!", "success");
      this.props.history.push(routes.ITEMS);
    }
  }

isLoading始终为假,因为由于接收速度快,我只是收到成功...

我尝试超时,并且100%的时间都在工作,但是我想要一个更干净的解决方案...

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

React的模型是一种更具声明性的方法,而您在componentDidUpdate中使用的代码是一种更具命令性的方法。通常,使用React,视图会根据应用程序的状态而变化,因此在渲染函数中,您会遇到类似

render() {
  if (this.props.loading) {
    return <LoadingComponent />
  }


  if (this.props.error) {
    return <ErrorSnackBar />
  }

  return <SuccessSnackBar />
}

这种声明性方法将使您的应用程序更易于长期推理和维护。

如果您确实需要为类似的内容使用命令式代码,那么您将希望将其精确地绑定到更改所依赖的状态部分。对于您的情况,要在出现错误时显示错误的小吃店,并在成功时显示成功的小吃店。您当前的代码不必要地将加载状态与视图的这些单独部分相关联。您可能想要使用类似的

componentDidUpdate(prevProps) {
  if (!prevProps.error && this.props.error) {
    // An error has occurred! Notice how *any* time an error occurs this
    // will run, not just when loading state changes
    this.enqueueSnackBar(this.props.error, 'error')
  }

  if (!prevProps.fetchedData && this.props.fetchedData) {
    // The data has been fetched! Do your stuff here.
    this.enqueueSnackBar("Success!", "success")
}
相关问题