为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

哔哔one 2021-04-19 16:13:08
我知道他们是类似的问题,但是我仍然对以下内容感到困惑。何时使用这样的状态Class Example extends Component {  state = {    name: ''  } }过度构造器道具Class Example extends Component{   constructor(props) {    super(props);    this.state = {      name: ''    }  }}它与方法绑定有关吗?因为我可以很好地使用onChange而不用像这样绑定它:this.onChange = this.onChange.bind(this) 我仍然可以像这样调用onChangeonChange = (e) => {}<Component onChange = {this.onChange} />
查看完整描述

2 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

在反应新版本中,您可以直接初始化状态,而无需使用此


constructor(Props){

super(props)

this.state ={

}

}


他们两个都是正确的。您可以使用其中任何一个。


我会选择第一个,因为它的代码更少


对于任何方法,您都可以直接使用它们,例如


  onChange = (e) => {


    }


<Component onChange = {this.onChange} />


在新版本的react中不需要绑定方法


查看完整回答
反对 回复 2021-04-29
?
翻阅古今

TA贡献1780条经验 获得超5个赞

您的示例中的差异纯粹是语法上的,而不是功能上的。您可以同时使用这两种效果。


通常,当您要基于某些运行时逻辑(例如,基于传递的props)来计算状态时,可以在构造函数中分配状态。在这种情况下,您将这样编写:


class Example extends Component {

  constructor(props) {

    this.state = {

      fullName: props.firstName + ' ' + props.lastName

    }

  }

}


查看完整回答
反对 回复 2021-04-29
  • 2 回答
  • 0 关注
  • 180 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信