React.js - 无法读取属性'罢工'未定义的错误

时间:2017-07-21 03:22:57

标签: javascript reactjs ecmascript-6

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

class App extends Component {
render() {
return (
  <div className="container">
    <LightningCounterDisplay/>
  </div>
   );
  }
}

class LightningCounter extends Component {
constructor(props) {
super(props);
this.state = {
  strikes : 0
};
}
timerTick() {
 this.setState({
  strikes: this.state.strikes + 100
 });
}
componentDidMount() {
setInterval(this.timerTick, 1000);
 }
render() {
  return (
  <h1>{this.state.strikes}</h1>
  );
 }
}

class LightningCounterDisplay extends Component {
 render() {
 const divStyle = {
  width: 250,
  textAligh: "center",
  backgroundColor: "black",
  padding: 40,
  fontFamily: "sans-serif",
  color: "#999",
  borderRadius: 10
}
return (
  <div style={divStyle}>
    <LightningCounter/>
  </div>

  );
 }
}

export default App;

我从昨天开始研究react.js和es6。

我试图在一秒钟内增加100分。 但是,它发生了TypeError:无法读取属性&#39; strikes&#39;未定义的。

你能说出问题出在哪里吗? 我该如何解决?

谢谢。

2 个答案:

答案 0 :(得分:2)

一种解决方案是使用bind,或者你也可以使用timerTick的箭头函数

timerTick = () => {
 this.setState(prevState => ({
  strikes: prevState.strikes + 100
 }));
}

使用箭头功能,使用setInterval(this.timerTick, 1000);即可。

答案 1 :(得分:0)

我通过&#39; bind&#39;解决了这个问题。

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

它有效,但这是正确的解决方案吗?