繁体   English   中英

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

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

我在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)

但没有一个有效。

这对我有用。 我返回的json是在解决了promise 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)
  })

我认为该错误在您的fetchWallsJson()函数中很明显。 在线response => 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.

暂无
暂无

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

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