[英]i can't save UseState get api in React
This is my output that I get from this GET url: https://localhost/get-all
but I can't save this value in the useState: const [dataCat, setDataCat] = useState([])
When I display it in控制台,它顯示正確,但它在 state 中返回一個空數組
{
"categories": [
{
"id": 1,
"name": "test1",
"slug": "intelligence-and-memory-tests",
"description": null,
},
{
"id": 2,
"name": "test2",
"slug": "occupational-and-organizational-tests",
"description": null,
},
{
"id": 3,
"name": "test3",
"slug": "love-and-marriage-tests",
},
]
}
這是我的使用效果:
useEffect(() => {
const fetchData = async () =>{
try {
const {data} = await axios.get('https://localhost/get-all');
console.log(data);
setDataCat(data)
} catch (error) {
console.error(error.message);
}
}
fetchData();
}, []);
您可以像這樣顯示它,它會將數據存儲在您的useState()
中。 我已經創建了formattedData
來重新創建您的 object
import { useEffect, useState } from "react";
import axios from "axios";
import "./styles.css";
export default function App() {
const [dataCat, setDataCat] = useState([]);
const [newDataCat, setNewDataCat] = useState([]);
// console.log("dataCat", dataCat);
// console.log("newDataCat", newDataCat);
const formattedData = (infoData) => {
let newDataCat = [];
infoData.forEach((item) =>
newDataCat.push({
id: item.id,
name: item.name,
slug: item.slug,
description: item.description
})
);
return newDataCat;
};
useEffect(() => {
const fetchData = async () => {
try {
const { data } = await axios.get(
"https://localhost/get-all"
);
setDataCat(data.categories);
} catch (error) {
console.error(error.message);
}
};
fetchData();
}, []);
useEffect(() => {
const cat = formattedData(dataCat);
setNewDataCat(cat);
}, [dataCat]);
return (
<>
{newDataCat &&
newDataCat.map((item) => {
return (
<>
<h2>{item.id}</h2>
<h2>{item.name}</h2>
<h2>{item.slug}</h2>
</>
);
})}
</>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.