首页 > 解决方案 > 不从道具初始化状​​态

问题描述

我正在使用 React 版本“17.0.1”,当我尝试从道具初始化组件状态时,它不起作用,它只是用未定义的状态初始化状态。以下示例将说明我的问题.. 组件Two

    class Two extends React.Component {
     state = {
       name: this.props.option.name
      }
     render(){
       console.log(this.state.name)

     return (
       <div>
          {this.state.name}
       </div>
      )
    }
}

组件One是:

    class One extends React.Component {
     render(){
        return  <Two option={name='riaz'} />
       }
     }

在组件中,Two我试图从道具初始化状​​态,但它只是用 undefined 初始化它

ReactDOM.render(<One />,document.getElementById('app'))

我已经安装并配置了@babel/plugin-proposal-class-properties

标签: reactjs

解决方案


您还应该像这样调用构造函数并初始化道具:

constructor(props) {
  super(props);
  this.state = {
       name: this.props.option.name
  }
}

否则 props 未定义,请查看官方文档:https ://reactjs.org/docs/react-component.html#constructor 。将 props 复制到 state 中仍然不是最佳实践。


推荐阅读