首页 > 解决方案 > 无法更新状态,出现“未定义”错误

问题描述

我正在尝试更新我的罢工,但是当我这样做时,出现错误

无法读取未定义的属性“罢工”

我的代码有什么错误?有人帮我弄清楚吗?

这是我的课:

无法读取未定义的属性“罢工”

    class LightningCounter extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          strikes: 0
        };
      }

      timerTick() {
        this.setState({
          strikes: this.state.strikes + 100 //getting red underline here
        });
      }

      componentDidMount() {
        setInterval(this.timerTick, 1000);
      }

      render() {
        return <h1>{this.state.strikes}</h1>;
      }
    }

标签: reactjsreact-native

解决方案


那是因为 this 关键字的上下文,this 计时器不知道它属于类,它指向自己作为函数。

现在像这样使用作为 ES6 标准的箭头函数

timerTick = () => {
`enter code here`
}

或在构造函数中以这种方式绑定函数

this.timerTick = this.timerTick.bind(this);

检查 bind 的文档以获得更清晰的信息

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

希望它有效


推荐阅读