javascript - React Native 中的 `fetch` 未从 URL 返回预期数据

标签 javascript reactjs react-native fetch redux

我想使用 fetch() API 从 React Native 应用程序中的 URL 加载数据。具体来说,我想加载 Hackernews Jobs 中的所有项目页面。

如他们的 API 文档中所述,相应的调用必须转到 URL:https://hacker-news.firebaseio.com/v0/jobstories.json

在浏览器中导航到此 URL 时,我按预期收到了一个简单的 javascript ID 数组:

[11379939,11379294,11378554,11377293,11375582,11373919,11372195,11371135,11369985,11369460,11361426,11357881,11356669,11354578,11351786,11350273,11349328,11347911,11346192,11343590,11342818,11342137,11341262,11340129]

但是,当我想使用以下方法在我的 React Native 应用程序中加载数据时,我收到的 javascript 数组与通过浏览器发送请求时收到的不同。

export const fetchJobs = () => {
  return (dispatch) => {
    return fetch('https://hacker-news.firebaseio.com/v0/jobstories.json', {
      method: 'GET',
      headers: {
        'Accept': 'application/json'
      }
    })
    .then( (response) => {
      console.log('Actions - fetchJobs - received response: ', response)
      const json = JSON.parse(response)
    })
    .then( (jobs) => {
      console.log('Actions - fetchJobs - received jobs: ', jobs)
      dispatch(receiveJobs(jobs))
    })
    .catch( (error) => {
      console.warn('Actions - fetchJobs - recreived error: ', error)
    })
  }
}

我在我的初始 React 组件中使用来自 Redux 的 dispatch 调用 fetchJobs(),如下所示:

componentDidMount() {
   var fetchJobsAction = fetchJobs()
   console.log('JobsRootComponent - fetch jobs: ' + fetchJobsAction)
   const { dispatch } = this.props
   dispatch( fetchJobs() )
}

但是,在 Chrome 调试控制台中检查输出时,输出如下所示:

enter image description here

有人能告诉我为什么我从浏览器发送的请求和我的 React Native 应用发送的请求的响应内容不同吗?

更新:根据评论中的要求,我现在也打印了 response.json(),结果如下: enter image description here

确实,数组数据现在似乎就在那里。但是我仍然不明白如何从我现在所在的位置访问它...

最佳答案

fetch 的响应有它自己的 JSON 解析函数,只需调用 response.json() 将返回一个新的 Promise。

fetch('https://hacker-news.firebaseio.com/v0/jobstories.json')
  .then(reponse => response.json())
  .then(json => console.log(json))

关于javascript - React Native 中的 `fetch` 未从 URL 返回预期数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36278879/

相关文章:

reactjs - POST 请求 : "Authentication credentials were not provided" using Axios, 的身份验证错误,但使用 POSTMAN 工作

react-native - 无法将 Android 手机连接到我的 Expo 项目

javascript - 刷新 iFrame(缓存问题)

javascript - 不要在 $location.hash 之后添加 hash 到 URL

javascript - React 在添加标签时无法删除重复项

react-native - react sectionList周围的原生边框半径

reactjs - 大量输入后 TextInput 变慢 React-native

javascript - 如果 hashMap 具有相同的键名称,如何获取对象数组中的所有值

javascript - 如果警报已经存在,确保警报框不会弹出的最佳方法是什么?

reactjs - 使用 typeof react Redux Action 类型