React Native 中的 `fetch` 没有 return 预期来自 URL 的数据

`fetch` in React Native doesn't return expected data from URL

我想使用 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 调试控制台中检查输出时,输出如下所示:

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

更新:按照评论中的要求,我现在也打印了response.json(),结果如下:

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

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

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

then

中使用return

你必须 return response.json() 的结果,如果你是 chaining then calls

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)
      return response.json();
    })
    .then( (jobs) => {
      console.log('Actions - fetchJobs - received jobs: ', jobs)
      dispatch(receiveJobs(jobs))
    })
    .catch( (error) => {
      console.warn('Actions - fetchJobs - recreived error: ', error)
    })
  }
}