ReactJS 在 prop 上获取新数据

ReactJS fetching new data on prop

作为序言,我对 React 还是个新手,所以我还在摸索。

我拥有的是一个获取数据以呈现 HTML table 的组件。因此,我从 componentWillMount() 中调用我的 Actions' fetchData()(它使用浏览器的 fetch() API),它也有一个用于存储更改的侦听器。这一切都很好,而且我能够检索和呈现数据。

现在下一步。我希望能够在更新组件的道具时获取新数据。但我不确定这样做的正确方法是什么。所以我有一个三部分的问题

  1. 当然,在确认道具确实发生变化后,在 componentWillReceiveProps() 中对新道具进行 fetchData() 的合适位置吗?
  2. 我的 API 相当慢,因此完全有可能在获取仍在 运行 时引入新道具。是否可以取消旧的提取并开始新的提取,或者至少实现忽略原始结果并等待更新的提取结果的逻辑?
  3. 与上述问题相关,除了在我的 Action 状态(或其他地方)中有类似 isLoading 布尔值之外,是否有一种方法可以确保任何时候只有一个提取是 运行?

是的,componentWillReceiveProps 是合适的地方。

关于第 2 点和第 3 点:

取消任务并保持'one fetch running'的想法似乎是不充分的。我不认为这种解决方案应该在任何系统中使用,因为实施会通过设计限制您的应用程序的效率。

Is it possible to cancel the old fetch and start a new one, or at least implement logic to ignore the original result and wait for the results from the newer fetch?

为什么不让 'newer fetch' 响应覆盖 'old fetch' 响应?

如果您真的想避免显示旧响应,您可以简单地使用所有 fetchData 调用的计数器来实现它。你可以这样实现:

var ApiClient = {
    processing: 0,
    fetchData: function(){
        processing++
        return yourLibForHTTPCall.get('http://endpoint').then(function (response)){
            processing--
            return response
        }
    },
    isIdle: function(){
        return processing == 0
    }   
}

以及您实际拨打电话的地点:

apiClient.fetchData(function(response){
    if(apiClient.isIdle()){
        this.setState({
      })
    }
}

我希望 yourLibForHTTPCall.get returns Promise 适合你的情况。