链式反应 setState 回调函数

5
我需要按顺序使用fetch方法加载三个不同的json文件(原因是我正在使用nextjs export,并且需要在需要时动态读取这些文件,因此我使用fetch方法来获取它们,即使在导出后它们的内容也可能会更改)。
第一个文件包含用于创建第二个文件的url的数据,以此类推,所以每个fetch都需要一个“实际更新”的状态来进行获取。
目前我正在使用的解决方案是,由于第二个和第三个文件分别依赖于第一个和第二个文件,因此我先获取第一个文件并使用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个回答

3

您不需要使用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
    });
  });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接