【发布时间】:2022-01-18 05:50:11
【问题描述】:
在我的代码下面,我想在开始渲染组件之前检索所有数据,有什么方法可以在 react 中做到这一点?我想这可能是一个简单的代码行,但由于我是编码新手,我仍然不知道所有反应组件的行为。谢谢你的回答。
import { useState, useEffect } from "react";
import axios from "axios";
import Cookies from "js-cookie";
// import material ui
import CircularProgress from "@mui/material/CircularProgress";
import Box from "@mui/material/Box";
// import config file
import { SERVER_URL } from "../../configEnv";
const Products = ({ catList }) => {
// catList is data coming from app.js file in format Array[objects...]
console.log("catList ==>", catList);
const [isLoading, setIsLoading] = useState(true);
const [dataSku, setDataSku] = useState([]);
console.log("datasku ==>", dataSku);
const tab = [];
useEffect(() => {
// Based on the catList tab I fetch additionnal data linked with each object of catList array
catList.slice(0, 2).forEach(async (element) => {
const { data } = await axios.post(`${SERVER_URL}/products`, {
product_skus: element.product_skus,
});
// The result I receive from the call is an array of objects that I push inside the Tab variable
tab.push({ name: element.name, content: data });
setDataSku(tab);
console.log("tab ==>", tab);
setIsLoading(false);
});
}, [catList]);
return isLoading ? (
<Box sx={{ display: "flex" }}>
{console.log("there")}
<CircularProgress />
</Box>
) : (
<div className="products-container">
<div>LEFT BAR</div>
<div>
{dataSku.map((elem) => {
return (
<div>
<h2>{elem.name}</h2>
</div>
);
})}
</div>
</div>
);
};
export default Products; ```
【问题讨论】:
-
如果你只获取一次数据,你的 useEffect() 钩子中需要一个空的依赖数组。
-
感谢您的回答,但是通过删除catList的依赖,useEffect内容不会被触发
-
您是否有机会更改 api 以便能够在一个请求中获取所有内容?执行异步 api 调用的 for 循环并不是最佳实践,因为它会引入多个故障点并增加网络流量
-
不幸的是我没有api ????所以我必须为每个 cat = category 请求调用
标签: javascript reactjs react-hooks components render