【发布时间】:2016-03-25 00:49:02
【问题描述】:
我在 react-native 中有一个状态变量 (wallsJSON),它应该保存从 URL http://unsplash.it/list 返回的 JSON 数据
所以在我的构造函数/getInitialState 中我有这样的变量设置
{
wallsJSON : []
}
我正在使用以下函数来获取 json 数据
fetchWallsJSON() {
var url = 'http://unsplash.it/list';
fetch(url)
.then( response => response.json())
.then( jsonData => {
this.setState({
isLoading: false,
wallsJSON: jsonData
});
})
.catch( error => console.log('JSON Fetch error : ' + error) );
}
我正面临这个错误:
JSON Fetch error : TypeError: In this environment the target of assign MUST be an object.This error is a performance optimization and not spec compliant.
我尝试使用下划线将返回的数据转换为使用_.object的Object,我也尝试了简单的wallsJson: Object(jsonData)
但没有一个有效。
【问题讨论】:
-
你确定你收到的数据是一个对象,你不用把结果当成
result = JSON.parse(data)吗? -
调用
response.json()应该返回获取数据的 json 形式,我尝试使用JSON.parse解析数据,但返回一个 Unexpected token 错误,猜猜这与服务器有关? -
试试这个!
fetch(url) .then( response => response.json() .then( jsonData => {...response.json() 之后可能还有一个额外的右括号 -
这实际上会导致语法错误
-
您的整个函数 fetchWallJSON 是否可能不知道 this?您能否在函数开始时通过
console.log(this)进行检查。
标签: javascript json reactjs react-native