链式react setState 回调

IT技术 javascript reactjs callback setstate chain
2021-05-02 15:34:02

我需要按顺序加载三个不同的 json 文件并使用 fetch(原因是我使用 nextjs 导出,我需要动态读取这些文件,所以我在需要时获取它们,即使在出口)

第一个文件包含用于为第二个文件创建 url 的数据,依此类推,因此每次获取都需要获取实际更新的状态,

ATM 我正在​​使用的解决方案,因为第二个和第三个文件分别依赖于第一个和第二个文件,正在获取第一个文件并使用 setState 设置一些状态,然后在 setState 回调中获取第二个文件并设置一些其他状态和很快:

fetch(baseUrl).then(
            response => response.json()
        ).then(
            res => { 
                this.setState({
                    ...
                }, () => {
                    fetch(anotherUrl+dataFromUpdatedState).then(
                        response => response.json()
                    ).then(
                        res => { 
                            this.setState({
                                ...
                            }, () => {                                 
                                fetch(anotherUrl+dataFromUpdatedState).then(
                                    response => response.json()
                                ).then(
                                    res => {
                                        this.setState({

                                        })
                                    }
                                )
                            })
                        }
                    ).catch(
                        error => {
                            //error handling
                        }
                    )
                })
            }
        ).catch(
            error => {
                this.setState({ //an error occured, fallback to default
                    market: defaultMarket,
                    language: defaultLanguage,
                    questions: defaultQuestions
                })
                //this.setLanguage();
            }
        )

现在:我知道 setState 必须谨慎使用,因为它是异步的,但据我所知,在状态更新后调用回调函数,因此从这个角度来看,状态应该正确更新。这种解决方案是反模式、不好的做法还是出于某种原因应该避免?

该代码实际上有效,但我不确定这是不是这样做的方法。

1个回答

您不需要使用setState回调并从状态中读取它,因为您可以直接从res对象中读取数据这样你就可以制作一个扁平的Promise链。

例子

fetch(baseUrl)
  .then(response => response.json())
  .then(res => {
    this.setState({
      // ...
    });

    return fetch(anotherUrl + dataFromRes);
  })
  .then(response => response.json())
  .then(res => {
    this.setState({
      // ...
    });

    return fetch(anotherUrl + dataFromRes);
  })
  .then(response => response.json())
  .then(res => {
    this.setState({
      // ...
    });
  })
  .catch(error => {
    this.setState({
      market: defaultMarket,
      language: defaultLanguage,
      questions: defaultQuestions
    });
  });