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

如何从状态访问卸载状态

如何从状态访问卸载状态

慕村225694 2021-04-30 08:11:29
当状态尚未挂载时,我想访问状态的属性。App类扩展了React.Component {    构造函数(道具){    超级(道具)    this.state = {       测试:2       得分:测试* 2    }}我想输入score4,但出现此错误:未定义“测试”PSscore: this.state.test也不起作用。
查看完整描述

2 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

您处于constructor,因此您可以更新状态,.setState()而不会产生任何后果,例如:


constructor(props) {

  super(props);

  this.state = {

    test: 2,

  };

  this.state.score = this.state.test * 2;

}


查看完整回答
反对 回复 2021-05-13
?
倚天杖

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

一种方法是在设置状态之前定义变量,然后使用它:


constructor(props) {

  super(props);

  const test = 2;

  this.state = {

    test,

    score: test * 2

  };

}


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

添加回答

举报

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