gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:13:23 25 4
gpt4 key购买 nike

我想使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com