【问题标题】:React / Redux - Dispatching several action too fastReact / Redux - 分派几个动作太快
【发布时间】:2019-06-03 22:31:00
【问题描述】:

我目前正在研究一个简单的用例:获取数据并显示它。 为此,我做了 3 个动作:加载、失败、成功,我根据我的功能调度。

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

我的代码是这样在获取数据时更新 UI 的:

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% 的时间都在工作,但我想要一个更清洁的解决方案...

有什么想法吗?

【问题讨论】:

  • 你能不能把你的action的代码贴出来
  • 对于我的数据获取操作,我使用 redux-saga。 saga 处理 fetch(不是 reducer),当它获得数据时,它会分派正确的事件(数据成功或错误),由 reducer 处理,相应地更新状态。

标签: reactjs redux react-redux


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-11-11
    • 1970-01-01
    • 2019-03-19
    • 2017-06-18
    • 2021-10-02
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    相关资源
    最近更新 更多