何时在构造函数(props)上使用纯状态?

我知道他们是类似的问题,但是我仍然对以下内容感到困惑。


何时使用这样的状态


Class Example extends Component {

  state = {

    name: ''

  }


 }

过度构造器道具


Class Example extends Component{ 


  constructor(props) {

    super(props);


    this.state = {

      name: ''

    }

  }

}

它与方法绑定有关吗?因为我可以很好地使用onChange而不用像这样绑定它:


this.onChange = this.onChange.bind(this) 

我仍然可以像这样调用onChange


onChange = (e) => {


}


<Component onChange = {this.onChange} />


哔哔one
浏览 181回答 2
2回答

蛊毒传说

在反应新版本中,您可以直接初始化状态,而无需使用此constructor(Props){super(props)this.state ={}}他们两个都是正确的。您可以使用其中任何一个。我会选择第一个,因为它的代码更少对于任何方法,您都可以直接使用它们,例如&nbsp; onChange = (e) => {&nbsp; &nbsp; }<Component onChange = {this.onChange} />在新版本的react中不需要绑定方法

翻阅古今

您的示例中的差异纯粹是语法上的,而不是功能上的。您可以同时使用这两种效果。通常,当您要基于某些运行时逻辑(例如,基于传递的props)来计算状态时,可以在构造函数中分配状态。在这种情况下,您将这样编写:class Example extends Component {&nbsp; constructor(props) {&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; fullName: props.firstName + ' ' + props.lastName&nbsp; &nbsp; }&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript