this.setState is undefined

前端 未结 8 2104
无人及你
无人及你 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 02:10

    in react native, we got this error when we use axios, as an example

        componentDidMount(){
        axios.get('https://the request url')
        .then( function(response) {
          this.setState({products:response.data.products});
        })
        .catch(function(error) {
          console.log(error);
        })
    }
    

    if we try like this we got :

    undefined is not an object (evaluating 'this.setState')

    so how we can fix this, we can fix it using arrow function like this

    componentDidMount(){
            axios.get('https://the request url')
            .then( (response)=> {
              this.setState({products:response.data.products});
            })
            .catch((error)=> {
              console.log(error);
            })
        }
    

    this will solve the problem, hope this will helpful

提交回复
热议问题