【问题标题】:TypeError: Cannont Read Property `State` of UndefinedTypeError:无法读取未定义的属性“状态”
【发布时间】:2019-07-25 17:32:18
【问题描述】:

得到错误:

TypeError:无法读取未定义的属性“状态”

当我要通过事件 onSubmit() 获取我的输入状态值时,我遇到了这个错误。

onFormSubmit(event){
    event.preventDefault();
    console.log(this.state.term);
}

【问题讨论】:

  • 在你的构造函数中,添加this.onFormSubmit = this.onFormSubmit.bind(this);
  • 或者把你的函数改成onFormSubmit = (event) =>
  • 绑定你的onFormSubmit this.onFormSubmit = this.onFormSubmit.bind(this);
  • 永远记住这一点:在调用它之前,你需要在构造函数中绑定你的函数。
  • 搜索错误会导致很多现有问题。

标签: javascript reactjs react-native


【解决方案1】:

请改用箭头函数:

改变

onFormSubmit(event){
    event.preventDefault();
    console.log(this.state.term);
}

onFormSubmit= (event)=>{
    event.preventDefault();
    console.log(this.state.term);
}

【讨论】:

    【解决方案2】:

    您没有上下文(this 未绑定到您的函数)。

    您可以使用以下方法之一解决此问题:

    首先,在构造函数中绑定 this

    constructor(props) {
      super(props);
      this.onFormSubmit = this.onFormSubmit.bind(this);
    }
    

    二、使用箭头函数

    onFormSubmit = (event) => {
      ...
    }
    

    第三,使用autobind-decorator之类的

    @boundMethod
    onFormSubmit(event) {
      ...
    }
    

    【讨论】:

      【解决方案3】:

      使用箭头函数 Like :

      onFormSubmit = (event) =>{
        event.preventDefault();
        console.log(this.state.term);
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-18
        • 2020-06-17
        • 2020-01-17
        • 2019-10-08
        • 1970-01-01
        • 1970-01-01
        • 2019-02-08
        相关资源
        最近更新 更多