在react components中,首选在构造函数()或componentWillMount()中设置初始状态吗?

exp或t default class MyComponent extends React.Component{
  construct或(props){
    super(props);
    this.setState({key: value});
  }
}

exp或t default class MyComponent extends React.Component{
  componentWillMount(props){
    this.setState({key: value});
  }
}

推荐答案

在使用ES6类时,最好使用构造函数,但不要使用setState API,而是这样做:

export default class MyComponent extends React.Component{
  constructor(props){
    super(props);
    this.state = { key: value };
  }
}

此外,如果您有可用的类属性(babel stage 1),则可以执行以下操作:

export default class MyComponent extends React.Component{
  state = { key: value };

  render() {
    ....
  }
}

Reactjs相关问答推荐

无法使用Apollo客户端GraphQL设置Next.js 14

有没有办法将MUI网格元素与Flex-Start对齐?

在REACT-RUTER-DOMV6中使用通用页面包装组件有问题吗?

如何使用 App Router 和服务器组件在 Next.js 13 中实现分页

获取 不能显示为 的后代.错误,但不太确定如何构建我的代码以避免此警告

i18next中复数键的理解

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

如何在next.js 13中仅在主页导航栏上隐藏组件?

未处理的拒绝 (TypeError):无法读取未定义的属性(读取协议)

在 CrafterCMS Studio 中拖动字段

React 组件列表中的第一个计时器正在获取值 NaN

try 从 React JS 构建此教程游戏但无法继续前进

如何在屏幕上使用相同的可重用

从服务器获取数据时未定义,错误非法调用

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

如何通过单击多个选项中的特定项目在模态上呈现不同的标题?

如何从 graphql/apollo 中的缓存中清除多个查询

理解 React 中的 PrevState

ReactJS:按钮启用禁用更改 colored颜色

运行开发服务器时如何为 Vite 指定运行时目录