Cannot read property 'setState' of undefined [duplicate]

。_饼干妹妹 提交于 2019-12-02 10:36:51

You're using function() in your Promise chain, this will change the scope for this. If you're using ES6 I suggest you use the arrow function to maintain the class scope. Example:

You're using

axios.get(APP_URL, { params: params})
    .then(function(response) { // this resets the scope
       this.setState({
           videos:response
       })
    })

Try using arrow functions:

axios.get(APP_URL, { params: params})
    .then((response) => {
       this.setState({
           videos:response
       })
    })

You also may need to add this.apiCall = this.apiCall.bind(this) before the this.apiCall('surfing'); on your constructor method. This will bind the scope of apiCall to the scope of the react component.

More here: https://facebook.github.io/react/docs/handling-events.html

Also, remove this.apiCall('surfing'); from the constructor and put it into a componentDidMount function, the constructor should not be used for execution.

It is due to scoping in your API call. The value of this is different within your response callback in your promise chain. There are two ways to solve this.

You could set a variable referencing this at the beginning of your apiCall method.

apiCall(term){

    const that = this;

    const params = {
        part: 'snippet',
        key:APP_KEY,
        q:term,
        type: 'video'
    };

   axios.get(APP_URL, { params: params}).then(function(response) {
       that.setState({
           videos:response
       });
    }).catch(function(error) {
       console.error(error);
  });

}

or else you can use ES6 arrow functions, which maintain the original scope, like this:

axios.get(APP_URL, { params: params}).then(response => {
    this.setState({
         videos:response
    });
})

You can assign the current context this to a variable, also be consistent either use ES5 or ES6.

apiCall(term) {
  const params = {
    part: 'snippet',
    key: APP_KEY,
    q: term,
    type: 'video'
  };
  const _this = this;

  axios.get(APP_URL, { params: params})
   .then((response) => {
     _this.setState({
       videos: response
     });
   })
   .catch((error) => {
    console.error(error);
   });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!