React中响应的使用

Usage of response in React

有人可以突出显示 React 中这 2 个代码片段之间的区别吗?

window.fetch(url)
  .then((response) => {
    console.log(response.json().content);
})

window.fetch(url)
  .then((response) =>  response.json())
  .then((data) =>{
    console.log(data.content);
})

response contains a Java object and content is one of the fields in that object.

第二个片段打印正确的内容值,而第一个片段打印未定义。

编辑:我的问题与 "why response gives a Promise rather than a normal object" 无关。它更多的是关于 response 返回承诺的含义。

下面的代码片段不起作用,因为 response.json() returns 一个 Promise 而不是一个简单的对象,这就是为什么在第二个代码片段中它 returns 是一个正确的值 using .then 获取值

window.fetch(url)
  .then((response) => {
    console.log(response.json().content); // response.json() is not an object but a promise and hence you can't access content from it directly
})

第二个片段等同于

window.fetch(url)
  .then((response) => {
    response.json().then((content) => console.log(content)); 
})

但是可以通过从第一个 .then 返回 response.json() promise 来简化为可链接的承诺,如第二个代码段所示

这是因为response.json()returnspromise.As it returns promise, so another then is used to catch its response. More info about promises can be found here.

在使用 javascript fetch 时,您需要使用 response.json() 将响应转换为 json。您可以使用 axios 跳过将响应转换为 json 的额外步骤,例如

axios.get(url)
  .then(res => {console.log(res)})