Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native - can't access setState inside component function

I'm learning react-native and now I'm stucked on state lesson with this error:

_this2.setState is not a function.

Here's the current block of code.

...
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?

like image 339
anderlaini Avatar asked Jul 13 '17 13:07

anderlaini


2 Answers

handleStartStopClick is called from a context where this is not your class's instance. You can avoid that by adding .bind(this) to the function you are passing as your click handler.

<TouchableHighlight onPress={this.handleStartStopClick.bind(this)}>
like image 80
Moti Azu Avatar answered Nov 19 '22 08:11

Moti Azu


Try this :

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

You must defined your function in constructor with bind(this) or

handleStartStopClick = () => {...}
like image 3
Voi Mập Avatar answered Nov 19 '22 10:11

Voi Mập