简体   繁体   English

React / React-Native无法将JSON数据分配给状态变量

[英]React/React-Native not able to assign JSON data to state variable

I have a state variable ( wallsJSON ) in react-native that is supposed to hold JSON data returned from the URL http://unsplash.it/list 我在react-native中有一个状态变量( wallsJSON ),应该保存从URL http://unsplash.it/list返回的JSON数据

So in my constructor/getInitialState I have the variable set up like this 所以在我的构造函数/ getInitialState中,我像这样设置了变量

{
  wallsJSON : []
}

I am using the following function to fetch the json data 我正在使用以下功能来获取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) );
  }

I am facing this 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.

I tried using underscore to convert the returned data to Object using _.object , also I tried simple wallsJson: Object(jsonData) 我尝试使用下划线使用_.object将返回的数据转换为Object,也尝试了简单的wallsJson: Object(jsonData)

but none of which worked. 但没有一个有效。

This works for me. 这对我有用。 The json I am returning comes after resolving the promise response.json() 我返回的json是在解决了promise response.json()

function fetch(url) {

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

If the above solution does not work, try the one from the documentation in github/fetch without using es6 arrow function. 如果上述解决方案不起作用,请尝试使用github / fetch中的文档,而不使用es6箭头功能。 This should work for sure. 这肯定可以工作。 We can then try converting the solution below to es6 syntax. 然后,我们可以尝试将以下解决方案转换为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)
  })

i think the error is obvious in your fetchWallsJson() function. 我认为该错误在您的fetchWallsJson()函数中很明显。 on the line response => response.json() your'e assing the results to the object json. 在线response => response.json()上,将结果关联到对象json。 so the next line should be 所以下一行应该是

.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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM