this.setState is undefined

前端 未结 8 2101
无人及你
无人及你 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

    The problem was: I had that ERROR: this.setState is not a function

    Given i was binding my function to the state in component constructor, like this:

     this.getRequestData = this.getRequestData.bind(this);
    

    and my function was:

    getRequestData(){
        axios.post('http://example.com/getInfo', jsonData)
                            .then(function (res) {
                                console.log(res);
                            })
                            .catch(function (error) {
                                console.log(error);
                            });
                            this.setState({ stateVaribale });
                        })
    }
    

    the solution is to use arrow functions instead of using keywordfunction in the axios request, cause it's confusing to react to refer to the function in axios request instead of the component state.

    getRequestData(){
    axios.post('http://example.com/getInfo', jsonData)
                            .then(res => {
                            console.log(res);
                            })
                            .catch(error => {
                                console.log(error);
                            });
                            this.setState({ stateVaribale });
                        })}
    

提交回复
热议问题