简体   繁体   English

在循环的每次迭代中使用 setState 是不好的做法吗?

[英]Is using setState in every iteration of a loop bad practice?

Here is a little code snippet:这是一个小代码片段:

async componentDidMount() {
    ...
    this.state.postList.forEach(element => {
      this.fetchItem(element);
    });
}

async fetchItem(query) {
    ...
    this.setState( previousState => {
        const list = [...previousState.data, data];
        return { data: list };
    });
}

I'm curious to know if using setState in every iteration of a forEach loop is a bad idea or not.我很想知道在forEach循环的每次迭代中使用setState是否是一个坏主意。 I'm suspecting that it impacts performance, but I'd like to know for sure because this seemed like the simplest solution to this problem.我怀疑它会影响性能,但我想确定,因为这似乎是解决这个问题的最简单的方法。

Here's an alternative approach: Update your fetchItem to just return the item.这是另一种方法:更新您的fetchItem以仅返回该项目。 In your componentDidMount use Promise.all to get all the items and then commit them to the state in a single operation.在您的componentDidMount中,使用Promise.all获取所有项目,然后在一次操作中将它们提交给 state。

async componentDidMount() {
    const items = await Promise.all(this.state.postList.map(element => fetchItem(element)));
    this.setState({data: items});
}

async fetchItem(query) {
    const item = await getItem(query) // however you accomplish this
    return item;
}

I'm curious to know if using setState in every iteration of a forEach loop is a bad idea or not.我很想知道在 forEach 循环的每次迭代中使用 setState 是否是一个坏主意。

If it would be directly inside of an iteration then definetly yes , as React than has to merge all the updates you make during the iteration, which will probably take much more time than if you would just set the state after the loop.如果它直接在迭代内部,那么肯定是 yes ,因为 React 必须合并你在迭代期间所做的所有更新,这可能比你在循环之后设置 state 花费更多的时间。 In your case however, you do start an asynchronous action in each iteration, and as all asynchronous tasks finish at different times, the updates aren't run all at once.但是,在您的情况下,您确实在每次迭代中启动了一个异步操作,并且由于所有异步任务在不同时间完成,因此更新不会一次全部运行。 The main benefit of your approach is that if these asynchronous tasks take some time (eg if you fetch a lot of data for each), then some information can already be shown, while some are still loading.您的方法的主要好处是,如果这些异步任务需要一些时间(例如,如果您为每个任务获取大量数据),那么已经可以显示一些信息,而有些信息仍在加载。 If all those asynchronous calls only load a small amount of data, well then you should actually change your API to deliver all the data at once.如果所有这些异步调用只加载少量数据,那么您实际上应该更改您的 API 以一次传送所有数据。 So it really depends on your usecase wether thats good or bad.所以这真的取决于你的用例是好是坏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM