[英]Fetch response gives JSON but needs to be `await` again, when used in a component
我正在尝试编写一个常见的 api 服务。 get.js 有'get' api 代码。 在 get.js 中,我看到了json
格式的response
。 但是当我在app.js
中调用它时,它没有在json
中收到,我必须再次await
才能使用它? 为什么?
// 获取.js
const getData = async (url) => {
try {
const response = await fetch(url);
const responseJson = await response.json();
console.log("responseJson: ", responseJson); // response is coming in json format
return responseJson; // returning that same `json`
} catch (error) {
console.log("Error: ", error);
}
return [];
};
export default getData;
responseJson
是 json 格式,正在returned
。
// 应用程序.js
import "./styles.css";
import getData from "./get";
import { useEffect, useState } from "react";
export default function App() {
const [demoData, setDemoData] = useState([]);
useEffect(() => {
async function fetchData() {
const json = await getData("https://jsonplaceholder.typicode.com/users"); // why again I need to 'await'? rather than directly using the json.
// console.log("json: ", json);
setDemoData(json);
}
fetchData();
}, []);
return (
<div className="App">
{demoData.map((data) => {
console.log("data: ", data);
return <p>{data.name}</p>;
})}
</div>
);
}
我必须await getData()
,为什么会这样?
CodeSandbox演示。
您的getData
function 是async
的,您必须在 app.js 文件中等待,因为getData
中的某些操作可能需要时间,而且您不会立即获得结果。
因此,在 app.js 文件中,您必须await
直到所有过程在getData
中完成,并且 json 响应从那里发回。
如果您不在app.js
中使用 await,那么在您收到 API 的响应之前,将执行该行之后的代码(您在其中调用 getData 方法)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.