【问题标题】:Parsing JSON in React Native fetch method doesnt work在 React Native fetch 方法中解析 JSON 不起作用
【发布时间】:2018-06-03 19:15:05
【问题描述】:

我试图通过从 React Native App 获取调用 API,但由于某种原因它没有记录响应数据 (console.warn('data', data))。它打印了“调用 getArtists”的日志,但没有任何反应。

const URL = 'https://jsonplaceholder.typicode.com/posts'

function getArtists(){
  console.log('call to getArtists')
  return fetch(URL)
    .then(response => response.json())
    .then(data => {
      console.warn('data', data)
    })
}

代码可在此处获得:https://snack.expo.io/rkzea2Zlm at components/api-client.js

我做错了什么?

【问题讨论】:

  • 你也需要回data
  • 我注意到使用URL = 'https://facebook.github.io/react-native/movies.json' 使请求有效。但其他人没有
  • 我注意到如果打印 responseJSON 而不是 data 它可以工作,但我不明白。我需要的真正 API(LastFM)不起作用

标签: api react-native fetch


【解决方案1】:

首先在“api_client.js”中,像下面的代码一样在里面放一个返回。

function getArtists(){
  console.log('call to getArtists')
  return fetch(URL)
    .then(response => response.json())
    .then(data => {
      return data
    })
}

在您的 App.js 中,只需在 componentWillMount 中执行此操作即可。

componentDidMount(){
    getArtists()
      .then(data => {
        alert(JSON.stringify(data))
      });
  }

【讨论】:

  • 你的获取中有一个错误的“then”,就像这段代码一样。 function getArtists(){ console.log('call to getArtists') return fetch(URL) .then(response => response.json()) .then(data => {return data}) }
  • 在 api_client.js 中的 getArtists() 方法中删除最后一个 then 后工作。我在 componentWillMount 中使用 alert(JSON.stringify(data)) 进行测试。
  • 谢谢!是的,似乎工作。但我不明白为什么console.log(data) 不打印信息但alert 打印。可能与零食有关(?)
  • 可能它不适用于两个参数(例如:console.log("teste", data))。如果你只插入一个参数就可以了。
猜你喜欢
  • 1970-01-01
  • 2016-08-12
  • 2019-09-18
  • 2018-03-31
  • 2017-10-21
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多