在componentDidMount()上设置状态
我知道将状态设置为打开是一种反模式,componentDidMount应该将状态设置为打开,componentWillMount但是假设我想将li标记数量的长度设置为状态。在那种情况下,我无法将状态设置为on,componentWillMount因为li在该阶段可能未安装标签。那么,这里最好的选择是什么?如果将状态设置为开启,会componentDidMount好吗?
回答:
这不是一个反模式调用setState在componentDidMount。实际上,ReactJS在其文档中提供了一个示例:
您应该在componentDidMount生命周期方法中使用AJAX调用填充数据。这样一来,您可以在检索数据时使用setState更新组件。
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
          });
        }
      )
  }
以上是 在componentDidMount()上设置状态 的全部内容, 来源链接: utcz.com/qa/400993.html







