this.setState is undefined

前端 未结 8 2085
无人及你
无人及你 2020-12-09 01:24

I keep seeing answers that say to use => or .bind(this) but neither of those solutions worked.

import React, { Component } from \'react\';
import { View, Tex         


        
8条回答
  •  天命终不由人
    2020-12-09 01:59

    Whenever you are using this inside an api call like axios request There are cases where your 'this' context remains to be undefined. Elaborating few of them here-:

    `

    import react from 'React'
    class Test extends from React.Component {
    constructor() {
    super();
    this.state = {
    data: '',
    error: ''
    }
    }
    componentDidMount() {
    url = 'http://abc.go.com';
    axios.get(url).then(function(resposne) {   // Everything fine till now
    this.setState({ data: response });   //Oops this context is undefined
    }
    ).catch(function(err) {
     this.setState({ error: err });       // again this context remains to be undefined
    });
    }
    render() {
    return ( 
    this.state.data
    ) } }`

    when you will run the above code you will definitely get a type error like setState of undefined is being called, Something similar to this.

    How can you solve this? There are two methods that you can follow to solve this particular type of question-:

    First one is you can define a variable inside the function where you'll be calling the api and assign it the value of 'this' and from that variable you can reference your state object.

    import react from 'React'
    class Test extends React.Component
    {
      constructor() { 
         super();
         this.state = {
           data: '',
           error: ''
      };
      componentDidMount() {
       let url = 'http://abc.go.com';
       currentContext = this;   // variable to be assigned this context
       axios.get(url).then(function(resposne) {   // Everything fine till now
       currentContext.setState({ data: response });   //Oops this context is undefined
       }
       ).catch(function(err) {
      currentContext.setState({ error: err });       // again this context remains to be undefined
     });
      }
     render() {
      return ( 
    this.state.data
    ) } }

    Second method that you can use is by defining arrow function in axios like given below

    axios.get(url).then((response) => {
      this.setState({ data: response })     //will always be bound to the this context
    }) 
    

提交回复
热议问题