React中fetch获取数据后setConfiguration设值为空数组问题求助
React中fetch获取数据后state无法更新的问题排查
接口返回的JSON结构
{ "Konfigurasi": [ { "id_konfigurasi": 1, "bahasa": "ID", "namaweb": "Universitas", "tagline": "home 2", "singkatan": "UBG", "id_user": 16, "periode_satu": "11 Desember 2023 s.d 30 April 2024 (Sudah Tutup)", "periode_dua": "1 Mei 2024 s.d 31 Juli 2024 (Sedang Dibuka)", "periode_tiga": "Belum Dibuka", "tanggal": "2023-05-10T02:44:44.000Z" } ] }
用户原始代码
const [configuration, setConfiguration] = useState([]); async function getConfiguration(){ const postData = { method: "GET", headers: { "Content-Type": "application/json" } } fetch(process.env.NEXT_PUBLIC_URL+'/api/Configuration',postData) .then(response => response.json()) .then(data => setConfiguration(data)) .catch(error => console.error(error)); } useEffect(()=>{ getConfiguration() },[])
问题原因
接口返回的JSON外层包含Konfigurasi字段,实际需要的数组数据嵌套在该字段下。当前代码直接将整个返回对象传给setConfiguration,但初始configuration是数组类型,导致state未被正确更新为目标数组。
修复后的代码
const [configuration, setConfiguration] = useState([]); async function getConfiguration(){ const postData = { method: "GET", headers: { "Content-Type": "application/json" } } fetch(process.env.NEXT_PUBLIC_URL+'/api/Configuration',postData) .then(response => response.json()) .then(data => { // 提取嵌套的Konfigurasi数组赋值给state setConfiguration(data.Konfigurasi); // 可选:打印数据确认结构 console.log('获取到的配置数组:', data.Konfigurasi); }) .catch(error => console.error(error)); } useEffect(()=>{ getConfiguration() },[])
额外注意事项
- 确认字段名拼写和大小写是否正确,比如接口返回的是大写开头的
Konfigurasi,避免因拼写错误导致无法提取数据。 - 初始state设为数组是合理的,因为
Konfigurasi本身就是数组类型,匹配类型后后续渲染时可直接遍历使用。
内容的提问来源于stack exchange,提问作者Rizki29
相关产品推荐
相关产品推荐

