Getting setState is not a function

后端 未结 2 1533
情歌与酒
情歌与酒 2021-01-29 06:07

I am getting the following error

//bundle.js:31367 Uncaught TypeError: this.setState is not a function//

JSX:

相关标签:
2条回答
  • 2021-01-29 07:01

    The problem is with Function Execution Scope.

    componentDidMount(){
        $.ajax({
          ...
        }).done(function({data}){
            ///// HERE {this}
            // try console.log(this);
            // you will see there is no`setState`
            this.setState({
                lis1:[data.banner]
            })
        })
    }
    

    Now, function inside the done chain, this reference only inside the function.

    Easy Fix:Use Fat Arror Function

    componentDidMount(){
        $.ajax({
            url:'',
            dataType:'json',
            cache:false,
        }).done(({data}) => {
            this.setState({
                lis1:[data.banner]
            })
        })
    }
    
    0 讨论(0)
  • 2021-01-29 07:04

    The problem is that this in your case doesn't represent the correct context. Function inside .done() represents a separate context for itself and thus either you can

    1. Add bind(this) after the .done().

    constructor(props){
        super(props);
        this.state={
    
            lis1:[],
    
        }
    
    }
    componentDidMount(){
        $.ajax({
            url:'',
            dataType:'json',
            cache:false,
        }).done(function({data}){
            this.setState({
                lis1:[data.banner]
            });
        }.bind(this));
    }
    

    2 Or you can assign this to a separate variable and use that.

    constructor(props){
        super(props);
        this.state={
    
            lis1:[],
    
        }
    
    }
    componentDidMount(){
        var self = this;
        $.ajax({
            url:'',
            dataType:'json',
            cache:false,
        }).done(function({data}){
            self.setState({
                lis1:[data.banner]
            })
        })
    }
    
    0 讨论(0)
提交回复
热议问题