Response-native - cannot access setState function inside component

I am studying a native reaction, and now I am stuck in a state lesson with this error:

_this2.setState is not a function.

Here is the current code block.

...
export default class StopWatch extends Component {

  constructor(props){
    super(props);
    this.state = {
      timeElapsed: null
    }
  }

  handleStartStopClick(){
    var startTime = new Date();

    setInterval(() => {
      this.setState(previousState => {
        return {timeElapsed:new Date() - startTime};
      });
    }, 100);
  }
...

What am I doing wrong?

+4
source share
2 answers

handleStartStopClickcalled from a context where thisit is not your class instance. You can avoid this by adding .bind(this)to the function that you pass as the click handler.

<TouchableHighlight onPress={this.handleStartStopClick.bind(this)}>
+7
source

Try the following:

 this.setState({timeElapsed : (new Date() - startTime)})

You must define your function in the constructor using bind (this) or

handleStartStopClick = () => {...}
+3
source

Source: https://habr.com/ru/post/1681368/


All Articles