Skip to content Skip to sidebar Skip to footer

Dont Understand State In React Js

But i trying. I need get json from api. I get error: TypeError: Cannot read property 'setState' of undefined(…) const Main = React.createClass({ getInitialState : function(

Solution 1:

componentDidMount: function() {  
     var self = this;
     axios.get('https://api')
         .then(function(response) {
            self.setState({data: response.data})
            console.log(response.data);
         })
         .catch(function(error) {
             console.log(error);
         });
        console.log('mount ' + self.state.data );
},

when this is being called its referring to the axios request not the component, so need to set a variable to the this that refers to your component instance that way when you do this.setState its coming from the right this

Solution 2:

when you use this you need to know how to use, because the context, you can do two things

 ...
 var setState = this.setState
 axios.get('https://api')
     .then(function (response) {
        setState({data: response.data})
     })
 ...

or you can do

 ...
 axios.get('https://api')
     .then(function (response) {
        this.setState({data: response.data})
     }.bind(this))
 ...

Post a Comment for "Dont Understand State In React Js"