获取 setState 不是一个函数

IT技术 ajax reactjs
2021-05-14 06:46:03

我收到以下错误

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

JSX:

  componentDidMount(){
    $.ajax({
        url:'http://intelligencevillage.wxtui.cn/index.php/Api/HomepageWebview/getHomepageData/area_id/5',
        dataType:'json',
        cache:false,
    }).done(function({data}){
        this.setState({
            lis1:[data.banner]
        })
    })
}

我知道这是某种绑定问题,但我不知道如何解决。任何帮助表示赞赏。

2个回答

问题在于函数执行范围。

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

现在,函数在done链中,this只在函数内部引用。

Easy Fix:使用 Fat Arror 功能

componentDidMount(){
    $.ajax({
        url:'',
        dataType:'json',
        cache:false,
    }).done(({data}) => {
        this.setState({
            lis1:[data.banner]
        })
    })
}

问题是this在您的情况下不代表正确的上下文。里面的函数.done()代表一个单独的上下文,因此你可以

1 . bind(this)之后添加.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 或者您可以分配this给一个单独的变量并使用它。

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]
        })
    })
}