可以使用useEffect钩子函数异步获取API数据,等数据返回后再更新useState状态。
示例代码:
import React, { useState, useEffect } from "react";
const ExampleComponent = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://exampleapi.com/data")
.then((response) => response.json())
.then((data) => setData(data))
.catch((error) => console.log(error))
}, []);
return (
{data.length !== 0 ? (
{data.map((item) => (
- {item.name}
))}
) : (
Loading...
)}
);
};
在这个例子中,useEffect异步地获取API数据,然后更新useState状态。当数据加载时,可以在组件中渲染出数据列表,完成数据的展示。
上一篇:API返回空数组
下一篇:API返回了400错误请求