【问题标题】:React - Uncaught TypeError: Cannot read property 'state' of > nullReact - 未捕获的类型错误:无法读取 > null 的属性“状态”
【发布时间】:2017-01-11 04:13:51
【问题描述】:

我有以下代码。它基本上只是一个带有事件处理程序的按钮,并且该类应该保持某种状态,到目前为止,它只是一个计数器,最初设置为 0。

import React, { Component } from 'react';
// import styles from './SentenceView.css';

export default class SentenceView extends Component {

  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  getNextSentence() {
    console.log(this.state.count); // this &
    this.setState({count: 2}); // this gives me an error
    console.log("Executed");
  }

  render() {
    return (
      <div>
        {/* <div className={styles.container}> */}
        <div>
          <h1>SentenceView</h1>
          <button onClick={this.getNextSentence}>Next Sentence</button>
        </div>
      </div>
    );
  }
}

当我点击 getNextSentence 按钮时,我得到:

SentenceView.js:14 Uncaught TypeError: Cannot read property 'state' of 空

我知道这个错误并不少见,但我还没有在这里找到任何解决方案。

【问题讨论】:

    标签: javascript reactjs electron


    【解决方案1】:

    尝试将其添加到底部的构造函数中:

    this.getNextSentence = this.getNextSentence.bind(this);
    

    【讨论】:

    • 我很惊讶这能奏效,因为我遇到了类似的东西,但无法让它发挥作用。这次成功了,所以谢谢你!我不太明白它的作用。您(或某人)能否(简要地)向我解释一下这到底是做什么的?
    • @GeorgeWelder 您可以在此处了解更多关于何时支持 ES6 类语法:facebook.github.io/react/blog/2015/01/27/…。本质上 - createClass 负责自动绑定 - 但是,使用类语法,您需要自己将 this 绑定到方法(否则在调用函数时您会失去对 this 的引用)
    【解决方案2】:

    组件不会像 createClass 这样的方法自动绑定 this。您需要在构造函数中将 this 绑定到 getNextSentence(或者您可以使用 es7 属性初始化器语法在类本身中进行绑定。)阅读更多 here

    【讨论】:

      【解决方案3】:

      您需要将该方法绑定到constructor 函数中的类,然后以与您在onClick 处理程序中的问题相同的方式引用它。

        constructor(props) {
          super(props);
          this.state = {
            count: 0
          };
          this.getNextSentence = this.getNextSentence.bind(this);
        }
      

      或者,您可以将bind 函数添加到SentenceView 类。

      <button onClick={this.getNextSentence.bind(this)}>
      

      但是,正如 Geoffrey Abdallah 在下面的评论中所解释的,在渲染中绑定将为每个渲染创建一个新函数。

      另一种选择是在您的 render 方法中利用 ES6 的 arrow 函数。

      <button onClick={() => this.getNextSentence()}>
      

      【讨论】:

      • 编辑删除评论 - 新编辑的答案显示构造函数中的绑定(渲染中的绑定将为每个渲染创建一个新函数)
      • 感谢@PaulFitzgerald!我完全同意,在大多数情况下,性能影响可以忽略不计(这就是为什么我在一些渲染中仍然有一些箭头函数。)只是想把这种方法绑定的被认为是“最佳实践”的东西扔掉。 .
      • @GeoffreyAbdallah 再次仅供参考,显然(根据那篇文章)首选方法是使用箭头函数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2016-09-13
      • 2022-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多