Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.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
Reactjs 什么';设置状态时,是什么导致了此打字错误?_Reactjs_React Native_Fetch - Fatal编程技术网

Reactjs 什么';设置状态时,是什么导致了此打字错误?

Reactjs 什么';设置状态时,是什么导致了此打字错误?,reactjs,react-native,fetch,Reactjs,React Native,Fetch,我正在尝试使用fetch从api获取数据。控制台日志为我提供了正确的json,但在尝试设置状态时出现以下错误: TypeError:无法读取未定义(…)的属性“setState” 看起来对“this”的引用不再指向正确的位置,请尝试执行以下操作: fetchFaqs() { var self = this; fetch(FAQ_API) .then(function(response){ return response.json();

我正在尝试使用fetch从api获取数据。控制台日志为我提供了正确的json,但在尝试设置状态时出现以下错误:

TypeError:无法读取未定义(…)的属性“setState”


看起来对“this”的引用不再指向正确的位置,请尝试执行以下操作:

fetchFaqs() {
var self = this;
    fetch(FAQ_API) 
        .then(function(response){
            return response.json();
        })
        .then(function(json){
            console.log("faqs: " , json);
            self.setState({
                faqs: json,
            });
        })
        .catch((error) => {
            console.warn(error);
        });
}
如果不想创建自变量,还可以将promise返回函数重构为es6 fat arrow函数,这将把它放在正确的范围内:

fetchFaqs() {
    fetch(FAQ_API) 
        .then((response) => {
            return response.json();
        })
        .then((json) => {
            this.setState({
                faqs: json,
            });
        })
        .catch((error) => {
            console.warn(error);
        });
}
fetchFaqs() {
    fetch(FAQ_API) 
        .then((response) => {
            return response.json();
        })
        .then((json) => {
            this.setState({
                faqs: json,
            });
        })
        .catch((error) => {
            console.warn(error);
        });
}