我知道将state设置为componentDidMount是一种反模式,state应该设置为componentWillMount,但是假设我想将li个标签的长度设置为state.在这种情况下,我无法将状态设置为componentWillMount,因为在该阶段可能没有安装li个标记.那么,什么是最好的 Select 呢?如果我把州定在componentDidMount,可以吗?

推荐答案

componentDidMount中调用setState并不是一种反模式.事实上,ReactJS在their documentation中提供了一个例子:

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

100

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
          });
        }
      )
  }

Reactjs相关问答推荐

webpack 5中动态导入的路径

NextJs Form不允许我输入任何输入,

从`redux—thunk`导入thunk `在stackblitz中不起作用

如何在MUI X数据网格列中显示IMG?

Redux工具包-useSelector如何通过Reducer引用InitialState?

更改滑块标记的文本 colored颜色 ./Reaction/MUI 5

有没有可能在next.js和ssr中使用tsps?

React 在第一次渲染时为 null

useEffect内部的RETURN语句在首次按钮点击事件中似乎无效的原因是什么?

React - 如何重定向页面以显示数据修改?

如何使用 React Hook Form 将寄存器作为 props 发送到子组件来收集数据?

Select 建议后如何关闭 vscode 添加自动完成={}

如何在对话素材ui中设置边框半径?

react 事件顺序

React Native map 中的初始zoom 级别

如何向 surveyjs 调查添加多个结尾?

在 Reactjs 中状态发生变化时渲染一个新组件而不替换旧组件

Cypress - 在继续之前等待下一个按钮重新出现

如果 URL 已随功能组件更改,则取消刷新

无法重用我的组件,它只显示 1 次