在 componentDidMount() 上设置状态

新手上路,请多包涵

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

原文由 Nirmalya Ghosh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 465
1 个回答

componentDidMount setState 不是反模式。事实上,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
          });
        }
      )
  }

原文由 lux 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进