【发布时间】:2016-07-16 16:31:31
【问题描述】:
我想使用fetch() API 从 React Native 应用程序中的 URL 加载数据。具体来说,我想从Hackernews Jobs 页面加载所有项目。
正如他们的 API 文档中所述,相应的调用必须转到 URL:https://hacker-news.firebaseio.com/v0/jobstories.json
在浏览器中导航到这个 URL 时,我收到了一个简单的 javascript 数组,如预期的那样:
[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 应用程序发送的请求之间的响应内容不同?
更新:按照 cmets 的要求,我现在也打印了 response.json(),结果如下:
确实,数组数据现在似乎在那里。但是我仍然不明白如何从我现在的位置访问它......
【问题讨论】:
-
你可以尝试打印 response.json() 吗?
-
当然,我刚刚做到了!将使用附加信息更新我的帖子!
-
尝试将
.then((response) => response.json())添加到您的链中,这应该会将您的响应转换为json
标签: javascript reactjs react-native fetch redux