我正在获取 API 并在产品数组中设置响应数据。但是,产品数组状态未更新并返回空数组。 这是我的代码,
const [products, setProducts] = useState([]);
useEffect(() => {
const apiCaller = async () => {
const res = await axios.get('http://127.0.0.1:2000/');
const pro = await res.data;
setProducts(pro);
console.log(products);
}
apiCaller();
}, []);
我尝试在依赖项数组中传递“产品”,但这会导致无限渲染。
您看不到该值的原因是,异步函数内第一次登录正在获取产品的先前状态是[],并且setProduct也是异步的,其更新不会立即反映在您将看到的同一渲染周期内useEffect 之外的更新产品
const [products, setProducts] = useState([]);
useEffect(() => {
const apiCaller = async () => {
const res = await axios.get('http://127.0.0.1:2000/');
const pro = res.data;
setProducts(pro);
};
apiCaller();
}, []);
// This will log the updated value of products whenever it changes
useEffect(() => {
console.log(products);
}, [products]);
// You can do this also
console.log(products);
卸载 useEffect 后状态会更新,您将获得一个空的产品数组。
因此,不要在 useEffect 内部打印产品,而是尝试在其外部写入。
const [products, setProducts] = useState([]);
useEffect(() => {
const apiCaller = async () => {
const res = await axios.get('http://127.0.0.1:2000/');
const pro = await res.data;
setProducts(pro);
}
apiCaller();
}, []);
console.log(products);
如果您想在收到数据后映射它,您可以在 useEffect 中执行如下操作:
const res = await axios.get('http://127.0.0.1:2000/');
const pro = await res.data;
pro.map((product,index)=>{
//// do the action here
})