Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React this.setState不是一个函数_Javascript_Reactjs - Fatal编程技术网

Javascript React this.setState不是一个函数

Javascript React this.setState不是一个函数,javascript,reactjs,Javascript,Reactjs,我是React的新手,我正在尝试编写一个使用API的应用程序。我不断地发现这个错误: TypeError:this.setState不是函数 当我尝试处理API响应时。我怀疑这个绑定有问题,但我不知道如何修复它。以下是我的组件的代码: var AppMain = React.createClass({ getInitialState: function() { return{ FirstName: " " }; },

我是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>
        );
    }
});
var-AppMain=React.createClass({
getInitialState:函数(){
返回{
名字:“
};
},
componentDidMount:function(){
init(函数(){
控制台信息(“API初始化成功”);
api('users.get',{fields:'photo_50'},函数(数据){
if(data.response){
this.setState({//)错误发生在此处
名字:data.response[0]。名字
});
console.info(this.state.FirstName);
}
});
},函数(){
控制台信息(“API初始化失败”);
}, '5.34');
},
render:function(){
返回(
);
}
});

回调是在不同的上下文中进行的。您需要将绑定到此,才能在回调中进行访问:

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

}.bind(this));
编辑: 看起来您必须同时绑定
init
api
调用:

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

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

    }, '5.34');

回调是在不同的上下文中进行的。您需要将绑定到此,才能在回调中进行访问:

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

}.bind(this));
编辑: 看起来您必须同时绑定
init
api
调用:

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

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

    }, '5.34');

在调用
api
方法之前,您还可以保存对
this
的引用:

componentDidMount:function(){

    var that = this;

    VK.init(function(){
        console.info("API initialisation successful");
        VK.api('users.get',{fields: 'photo_50'},function(data){
            if(data.response){
                that.setState({ //the error happens here
                    FirstName: data.response[0].first_name
                });
                console.info(that.state.FirstName);
            }
        });
    }, function(){
        console.info("API initialisation failed");

    }, '5.34');
},

在调用
api
方法之前,您还可以保存对
this
的引用:

componentDidMount:function(){

    var that = this;

    VK.init(function(){
        console.info("API initialisation successful");
        VK.api('users.get',{fields: 'photo_50'},function(data){
            if(data.response){
                that.setState({ //the error happens here
                    FirstName: data.response[0].first_name
                });
                console.info(that.state.FirstName);
            }
        });
    }, function(){
        console.info("API initialisation failed");

    }, '5.34');
},

您可以使用ES6 arrow函数避免.bind(this)的需要

VK.api('users.get',{fields: 'photo_50'},(data) => {
        if(data.response){
            this.setState({ //the error happens here
                FirstName: data.response[0].first_name
            });
            console.info(this.state.FirstName);
        }

    });

您可以使用ES6 arrow函数避免.bind(this)的需要

VK.api('users.get',{fields: 'photo_50'},(data) => {
        if(data.response){
            this.setState({ //the error happens here
                FirstName: data.response[0].first_name
            });
            console.info(this.state.FirstName);
        }

    });

现在ES6有了箭头函数,如果你真的混淆了bind(这个)表达式,你可以试试箭头函数

我就是这样做的

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

现在ES6有了箭头函数,如果你真的混淆了bind(这个)表达式,你可以试试箭头函数

我就是这样做的

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

现在,在react with es6/7中,您可以使用箭头函数将函数绑定到当前上下文,如下所示,发出请求并解决承诺:

listMovies = async () => {
 const request = await VK.api('users.get',{fields: 'photo_50'});
 const data = await request.json()
 if (data) {
  this.setState({movies: data})
 }
}
使用此方法,您可以在componentDidMount中轻松调用此函数,并在呈现函数中呈现html之前等待数据

VK.api('users.get',{fields: 'photo_50'},(data) => {
        if(data.response){
            this.setState({ //the error happens here
                FirstName: data.response[0].first_name
            });
            console.info(this.state.FirstName);
        }

    });
我不知道您的项目的大小,但我个人建议不要使用组件的当前状态来操作数据。
您应该使用外部状态,如Redux或Flux或其他一些

现在,在react with es6/7中,您可以使用如下箭头函数将函数绑定到当前上下文,发出请求并解决承诺:

listMovies = async () => {
 const request = await VK.api('users.get',{fields: 'photo_50'});
 const data = await request.json()
 if (data) {
  this.setState({movies: data})
 }
}
使用此方法,您可以在componentDidMount中轻松调用此函数,并在呈现函数中呈现html之前等待数据

VK.api('users.get',{fields: 'photo_50'},(data) => {
        if(data.response){
            this.setState({ //the error happens here
                FirstName: data.response[0].first_name
            });
            console.info(this.state.FirstName);
        }

    });
我不知道您的项目的大小,但我个人建议不要使用组件的当前状态来操作数据。
您应该使用外部状态,如Redux或Flux或其他一些

您只需绑定事件即可

例如—

// 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});

}

您只需要绑定您的事件

例如—

// 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});

}

如果使用arrow函数,则无需将其指定给局部变量。Arrow函数自动进行绑定,您可以避开与范围相关的问题

下面的代码解释了如何在不同的场景中使用箭头函数

componentDidMount = () => {

    VK.init(() => {
        console.info("API initialisation successful");
        VK.api('users.get',{fields: 'photo_50'},(data) => {
            if(data.response){
                that.setState({ //this available here and you can do setState
                    FirstName: data.response[0].first_name
                });
                console.info(that.state.FirstName);
            }
        });
    }, () => {
        console.info("API initialisation failed");

    }, '5.34');
 },

如果使用arrow函数,则无需将其指定给局部变量。Arrow函数自动进行绑定,您可以避开与范围相关的问题

下面的代码解释了如何在不同的场景中使用箭头函数

componentDidMount = () => {

    VK.init(() => {
        console.info("API initialisation successful");
        VK.api('users.get',{fields: 'photo_50'},(data) => {
            if(data.response){
                that.setState({ //this available here and you can do setState
                    FirstName: data.response[0].first_name
                });
                console.info(that.state.FirstName);
            }
        });
    }, () => {
        console.info("API initialisation failed");

    }, '5.34');
 },

React建议在需要使用
类的this而不是self
函数的所有方法中绑定此函数

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

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

或者您可以使用
箭头函数

React建议在所有需要使用
而非self
函数的方法中绑定此函数

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

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

或者您可以改用
箭头函数

这里的上下文正在更改。使用arrow函数保留React类的上下文

        VK.init(() => {
            console.info("API initialisation successful");
            VK.api('users.get',{fields: 'photo_50'},(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');

在这里,这种情况正在发生变化。使用arrow函数保留React类的上下文

        VK.init(() => {
            console.info("API initialisation successful");
            VK.api('users.get',{fields: 'photo_50'},(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');

如果你这么做的时候仍然有问题,我的问题是我调用了两个同名的变量


我把
companys
作为从Firebase引入的对象,然后试图调用
this.setState({companys:companys})
-由于明显的原因,它不起作用。

如果你这样做时仍然有问题,我的问题是我调用了两个同名变量


我把
companys
作为从Firebase引入的对象,然后试图调用
this.setState({companys:companys})
-由于明显的原因,它不起作用。

使用箭头函数,因为箭头函数指向父范围,这将可用。
(绑定技术的替代)

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

这很有效。事实上,函数的关键字不应该出现在es6文件中。您的回答帮助了我:-)使用es6类和RN 0.34,我找到了两种方法将“this”绑定到回调函数。1)
onChange={(选中)=>this.toggleCheckbox()}
,2)
onChange={this.toggleCheckbox.bind(this)}
。只要您不需要支持旧浏览器,这很好。完美的解决方案gmsof,这两个解决方案都可以工作,因为a)当您执行
.bind(this)
时,它将
this
的值设置为父上下文,其中
this.toggleChe