反应this.setState不是一个函数

JavaScript

Stafan小宇宙

2020-03-10

我是React的新手,正在尝试编写使用API​​的应用程序。我不断收到此错误:

TypeError:this.setState不是一个函数

当我尝试处理API响应时。我怀疑此绑定有问题,但我不知道如何解决它。这是我组件的代码:

var AppMain = React.createClass({
    getInitialState: function() {
        return{
            FirstName: " "
        };
    },
    componentDidMount:function(){
        VK.init(function(){
            console.info("API initialisation successful");
            VK.api('users.get',{fields: 'photo_50'},function(data){
                if(data.response){
                    this.setState({ //the error happens here
                        FirstName: data.response[0].first_name
                    });
                    console.info(this.state.FirstName);
                }

            });
        }, function(){
        console.info("API initialisation failed");

        }, '5.34');
    },
    render:function(){
        return (
            <div className="appMain">
            <Header  />
            </div>
        );
    }
});

第444篇《反应this.setState不是一个函数》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
神乐蛋蛋 2020.03.10

使用箭头函数,因为箭头函数指向父级作用域,因此将可用。(代替绑定技术)

LEYMandy 2020.03.10

现在,ES6具有箭头功能,如果您确实与bind(this)表达式混淆,可以尝试使用箭头功能

我就是这样

componentWillMount() {
        ListApi.getList()
            .then(JsonList => this.setState({ List: JsonList }));
    }

 //Above method equalent to this...
     componentWillMount() {
         ListApi.getList()
             .then(function (JsonList) {
                 this.setState({ List: JsonList });
             }.bind(this));
 }
西里西门 2020.03.10

您只需要绑定事件

对于前

// place this code to your constructor

this._handleDelete = this._handleDelete.bind(this);

// and your setState function will work perfectly

_handleDelete(id){

    this.state.list.splice(id, 1);

    this.setState({ list: this.state.list });

    // this.setState({list: list});

}
TomGO 2020.03.10

React建议在需要使用this class而不是self的所有方法中将此绑定function

constructor(props) {
    super(props)
    this.onClick = this.onClick.bind(this)
}

 onClick () {
     this.setState({...})
 }

或者您也可以使用arrow function

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android