react-native fetch 下面的代码片段中的
then(res => res.json())
是什么意思?
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({
data: res,
error: res.error || null,
loading: false
});
这并不是一个真正的反应问题,因为 fetch 和 then 是 js 本身的一部分。
fetch 返回一个 Promise 对象,其中包含各种信息,如标头、HTTP 状态等。
你有
res.json()
和各种其他可能性。 .json()
将仅返回带有 json 内容的承诺正文。
了解更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
您可以按如下方式返回数据:
.arrayBuffer()
.blob()
.json()
.text()
.formData()
fetch
函数从指定的 url
异步提取资源。同时 fetch
返回 Promise
。 Promise
有助于异步部分,并在以获取的资源作为参数加载资源后运行传递到 then
(res => res.json()
) 的函数。如果获取的资源是 JSON 格式,则可以使用 json()
来解析。
then
还返回 Promise
使其可链接。
fetch(url) // asynchronously load contents of the url
// return a Promise that resolves when res is loaded
.then(res => res.json()) // call this function when res is loaded
// return a Promise with result of above function
.then(res => { // call this function when the above chained Promise resolves
this.setState({
data: res,
error: res.error || null,
loading: false
});
res => res.json()
也可以写成(但不完全等于)
function(res) { return res.json()}