【问题标题】:React/React-Native not able to assign JSON data to state variableReact/React-Native 无法将 JSON 数据分配给状态变量
【发布时间】: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


【解决方案1】:

我认为错误在您的 fetchWallsJson() 函数中很明显。 在响应 => response.json() 线上,您将结果分配给对象 json。 所以下一行应该是

.then(json => { this.setState({
   isLoading: true,
   wallsJson: json, //json.results or something likes that(highly likely)          
          }) 
)

//which would be the same object you assinged your response to.

【讨论】:

    【解决方案2】:

    这对我有用。我要返回的json 是在解决了response.json() 的承诺之后出现的

    function fetch(url) {
    
      return fetch(url).then(response =>
        response.json().then(json => {
          return json;
        })
      );
    }
    

    如果上述解决方案不起作用,请尝试github/fetch 中的文档中的一种,而不使用 es6 箭头功能。这应该肯定有效。然后我们可以尝试将下面的解决方案转换为 es6 语法。

    fetch('/users.json')
      .then(function(response) {
        return response.json()
      }).then(function(json) {
        console.log('parsed json', json)
      }).catch(function(ex) {
        console.log('parsing failed', ex)
      })
    

    【讨论】:

    • 当您将responsejsonData 打印到控制台时,它是什么样子的? jsonData 是对象吗?
    • 它是一个数组而不是一个对象!哦,我的坏。我没有看到它首先被定义为一个数组。您根本不必调用 response.json()。如果您将响应存储在您的状态中,那就是它!
    • 数组的类型也不是对象,并且您所说的响应不是普通数组或对象,它在其中定义了其他函数,例如 json() 和 text() 以便不能赋值给状态变量
    • 是的,你是对的。您发送的 png 是哪个变量的结果:responsejsonData?如果它的响应,那么它没有标题和其他细节。如果它是jsonData,那么错误可能是因为您正在尝试分配一个数组...我不确定。另外,请参考stackoverflow.com/questions/26253351/…
    • 这是 jsonData,直到昨晚一切正常,然后他们的 API 今天早上出现故障,最近又出现了这个错误..我也不确定 XD 无论如何谢谢
    猜你喜欢
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 2018-05-17
    • 1970-01-01
    相关资源
    最近更新 更多