useState 返回空数组
useState returning empty array
我有这个非常简单的代码
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 只有 returns 一个空数组,我需要映射该数据,以便显示它。
图片如下:
我做错了什么?
提前致谢。
因为状态只在组件重新渲染时渲染。所以将 console.log(bands);
放在 useEffect
之外,以便在组件渲染时看到新值
useEffect(() => {
const loadBands = async () => {
const response = await api.get();
setBands(response.data);
console.log(response.data);
};
loadBands();
}, []);
console.log(bands);
我有这个非常简单的代码
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 只有 returns 一个空数组,我需要映射该数据,以便显示它。
图片如下:
我做错了什么?
提前致谢。
因为状态只在组件重新渲染时渲染。所以将 console.log(bands);
放在 useEffect
之外,以便在组件渲染时看到新值
useEffect(() => {
const loadBands = async () => {
const response = await api.get();
setBands(response.data);
console.log(response.data);
};
loadBands();
}, []);
console.log(bands);