【问题标题】:why would this.state not be available in this scenario?为什么 this.state 在这种情况下不可用?
【发布时间】:2020-04-21 08:03:30
【问题描述】:

我有一个具有以下功能的组件:

constructor(MyProps: Readonly<MyProps>){
    super(MyProps);
    this.state = {suppliers: [], supplierId:0, supplierName:''};
    this.addSupplier.bind(this);
  }

addSupplier(){
    const {supplierId} = this.state;
    alert('supplierId = ' + supplierId);
}

<Button onClick={this.addSupplier}>Add</Button>

状态按预期初始化 b/c this.state.supplierId 在加载时在组件的 html 输入中按预期绑定和显示。 html 输入中的 onChange 处理程序也按预期调用 setState 来更新 state.supplierId。但是,当 addSupplier() 按钮被触发时,会出现以下错误:

TypeError: 无法读取未定义的属性 'supplierId'

因此,由于某种原因,状态在此上下文中不可用。知道这是为什么吗?

【问题讨论】:

标签: reactjs typescript


【解决方案1】:

请使用箭头函数创建方法

addSupplier = () => {}

或者在构造函数中使用下面的语法

this.addSupplier = this.addSupplier.bind(this);

【讨论】:

    【解决方案2】:

    为了扩展 Nikhil Goyal 发布的内容,您收到错误的原因是因为调用该函数的 this 的上下文。非箭头函数在调用时隐式绑定其上下文,而不是在声明它们时。因此,当您在 Button 组件上按下 onClick 时,它会在 Button 上下文中搜索 this.state.supplierId

    【讨论】:

      猜你喜欢
      • 2017-01-07
      • 2021-08-09
      • 2017-11-26
      • 2010-12-29
      • 1970-01-01
      • 2014-03-24
      • 2021-08-05
      • 2011-11-14
      • 1970-01-01
      相关资源
      最近更新 更多