运行setState后所有状态为空



作为一个初学者,我在做一个简单的API请求和循环状态时遇到了麻烦。API路由返回已测试的请求数据,所以我认为后端不是麻烦。我认为真正棘手的错误肯定与反应有关。我设置了几个状态,并使用useEffect调用一个函数,其中将使用axios请求数据。数据返回,setstate实际工作。当还检查来自浏览器react扩展的状态值时,它还显示数据已经处于该状态。如果状态被控制台记录并通过浏览器上的控制台进行检查。它显示有数据。

但这就是它变得有趣的地方。即使在axios请求数据并运行setState工作的函数内部执行控制台日志,但在函数外部执行控制台日志时,也会显示没有任何状态具有数据。但是浏览器扩展工具仍然显示状态中有数据。

并且循环状态根本不起作用,因为它显然没有数据。真的越来越奇怪了。因为浏览器显示状态中有数据,但当实际循环它或运行控制台日志时,它根本不显示任何内容。

import axios from "axios";
import React, { Fragment, useEffect, useState } from "react";
import Spinner from "../Component/Spinner";
export default function Home() {
const [category, setCategory] = useState([]);
const [productByCategory, setProductByCategory] = useState([]);
const [loader, setLoader] = useState(true);
const [featureProduct, setFeatureProduct] = useState([]);
const fetchProduct = () => {
axios.get("/api/home").then((d) => {
const { category, featureProduct, productByCategory } = d.data.data;
setCategory(category);
setFeatureProduct(featureProduct);
setProductByCategory(productByCategory);
setLoader(false);
});
};
useEffect(() => {
fetchProduct();
}, []);

return (
<Fragment>
{loader && <Spinner />}
{!loader && (
<Fragment>
<div className="w-80 mt-5">
<div className="row mt-2">
{/* loop category */}
{category.map((c) => {
<div
className="col-12 col-sm-12 col-md-3 col-lg-3 border"
key={c.slug}
>
<a href="" className="text-dark">
<div className="d-flex justify-content-around align-items-center p-3">

<img
src={c.image}
width={100}
alt=""
/>
<div className="text-center">
<p className="fs-2">{c.name}</p>
<small className="">
{c.product_count}
</small>
</div>
</div>
</a>
</div>;
})}
</div>
</div>

你没有从地图返回任何东西。此外,console.log不会显示数据,因为setState是异步的,所以日志在设置状态之前运行。为什么setState在reactjs Async而不是Sync?

category.map((c) => {
//return missing
return <div className="col-12 col-sm-12 col-md-3 col-lg-3 border" key={c.slug}>
<a href="" className="text-dark">
<div className="d-flex justify-content-around align-items-center p-3">
<img src={c.image} width={100} alt="" />
<div className="text-center">
<p className="fs-2">{c.name}</p>
<small className="">{c.product_count}</small>
</div>
</div>
</a>
</div>;
})

相关内容

最新更新