小编典典

在componentDidMount()上设置状态

reactjs

我知道将状态设置为打开是一种反模式,componentDidMount应该将状态设置为打开,componentWillMount但是假设我想将li标记数量的长度设置为状态。在那种情况下,我无法将状态设置为on,componentWillMount因为li在该阶段可能未安装标签。那么,这里最好的选择是什么?如果将状态设置为开启,会componentDidMount好吗?


阅读 443

收藏
2020-07-22

共1个答案

小编典典

这不是一个反模式调用setStatecomponentDidMount。实际上,ReactJS在其文档中提供了一个示例:

您应该在componentDidMount生命周期方法中使用AJAX调用填充数据。这样一来,您可以在检索数据时使用setState更新组件。

Doc中的示例

componentDidMount() {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }
2020-07-22