在componentDidMount()上设置状态

时间:2016-03-07 17:29:13

标签: reactjs

我知道在componentDidMount上设置状态是一种反模式,并且应该在componentWillMount上设置状态,但是假设我想设置li的数量的长度标签作为一个州。在这种情况下,我无法在componentWillMount上设置状态,因为在此阶段可能尚未安装li标记。那么,这里最好的选择是什么?如果我在componentDidMount上设置状态,那会没关系吗?

4 个答案:

答案 0 :(得分:61)

setState中调用componentDidMount并非反模式。实际上,ReactJS在their documentation中提供了一个示例:

  

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

<强> Example From 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
          });
        }
      )
  }

答案 1 :(得分:1)

根据React文档,完全可以从setState()函数中调用componentDidMount()

这将导致render()被调用两次,这比仅调用一次效率低,但除此之外,它还可以。

您可以在此处找到文档:

https://reactjs.org/docs/react-component.html

以下是文档摘录:

  

您可以立即在componentDidMount()中调用setState()。它会   触发额外的渲染,但这将在浏览器之前发生   更新屏幕。这样可以保证即使render()   在这种情况下被两次调用,用户将看不到中间   州。请谨慎使用此模式,因为它经常会导致   性能问题...

答案 2 :(得分:1)

lint抱怨在setState({..})componentDidMount中使用componentDidUpdate的唯一原因是,当组件渲染setState时,立即导致组件重新渲染。 但是要注意的最重要的一点是:在这些组件的生命周期中使用它并不是React中的反模式。

请查看此issue。您将了解有关此主题的更多信息。 感谢您阅读我的回答。

答案 3 :(得分:-1)

如果要将道具传递给组件,并且想要根据道具更新状态,则必须使用setTimeout或setInterval或发送AJAX请求。

this.state = {
    favourite: null,
    job_applied: null,
}

componentDidMount() {
    setTimeout(() => {
        if (this.props.wishlist == true) {
            this.setState({ favourite: true });
        }
        if (this.props.job_applied == true) {
            this.setState({ job_applied: true });
        }
    }, 300)
}
相关问题