无法更新状态,错误为“未定义”

时间:2018-08-09 07:27:04

标签: reactjs react-native

我正在尝试更新我的警示,但是当我这样做时,却报错了

  

无法读取未定义的属性“警示”

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

这是我的课:

无法读取未定义的属性“警示”

    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>;
      }
    }

1 个答案:

答案 0 :(得分:3)

那是因为该关键字的上下文, 这个timertick不知道它属于类,它指向自身为函数。

使用箭头功能(现在是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

希望它能起作用