作为初学者,我在做一个简单的API请求和循环状态方面遇到了困难。API路由返回已测试过的数据,因此我认为后端不是麻烦。我认为,真正棘手的错误肯定与反应有关。我设置了几个状态,并使用useEffect调用一个函数,其中将使用axios请求数据。数据返回和setStae实际上可以工作。在检查来自浏览器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>发布于 2022-07-15 14:03:17
你不能从地图上退货。另外,console.log不会显示数据,因为setState是异步的,因此日志在设置状态之前运行。在这里阅读更多Why is setState in reactjs Async instead of 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>;
})https://stackoverflow.com/questions/72994868
复制相似问题