使用 axios 从 GET 请求中提取数据



我遇到了从axios GET请求中提取数据的问题。下面是我的代码:

const Product = () => {
const [cars, setCar] = useState([]);
useEffect(() => {
const fetchPosts = async () => {
const res = await axios.get("http://192.168.29.135:8000/data/cars");
//console.log(res);
setCar(res.data);
console.log(typeof res.data);
console.log(res.data);
console.log(cars);
};
fetchPosts();
}, []);
return <div>{cars.car_name}</div>;
}

console.log(res.data) 的输出是这样的:

{status: 1, message: "Cars List", data: Array(30)}
data: (30) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
message: "Cars List"
status: 1
__proto__: Object

控制台.log(汽车)的输出为

定义

因此,我无法使用地图功能,该函数给我错误"地图不是函数。我想我需要使用这个setCar(res.data.data)。但即使这样也行不通。我哪里出错了?感谢您的帮助。

setCar是异步的,因此在设置后无法立即获得cars,这就是为什么您在console.logundefined的原因。

但是,汽车被正确设置为状态,但由于它是一个列表,您只能通过它map才能访问这些值。

考虑重构useEffect,使其仅在数据可用时setCars

useEffect(() => {
const fetchPosts = async () => {
const res = await axios.get("http://192.168.29.135:8000/data/cars");
if (res.data) {
setCar(res.data);
}
};
fetchPosts();
}, []);

所以你的return应该像这样返回 JSX

return (
<div>
{cars.map(car => 
<span key={car.id}>
{car.car_name}
</span>
)}
</div>
);

最新更新