reactjs useState返回空数组

abithluo  于 2022-12-12  发布在  React
关注(0)|答案(1)|浏览(148)

我有一个非常简单的代码

import React, { useEffect, useState } from "react";

import api from "../assets/services/api.js";

const Teste = () => {
    const [searchBand, setSearchBand] = useState("");
    const [bands, setBands] = useState([]);
    useEffect(() => {
        const loadBands = async () => {
            const response = await api.get();
            setBands(response.data);
            console.log(response.data);
            console.log(bands);
        };
        loadBands();
    }, []);

从Strapi那里获取数据。问题是:bands只返回一个空数组,我需要Map该数据,以便显示它。
以下是图像:

我做错了什么?
先谢谢你。

dvtswwa3

dvtswwa31#

因为state只在组件重新呈现时才呈现,所以把console.log(bands);放在useEffect之外,在组件呈现时才能看到新的值

useEffect(() => {
    const loadBands = async () => {
        const response = await api.get();
        setBands(response.data);
        console.log(response.data);
    };
    loadBands();
}, []);

console.log(bands);

相关问题