[英]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 the console, it is displayed correctly, but it returns an empty array in the state 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",
},
]
}
this is my useEffect:这是我的使用效果:
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();
}, []);
You can display it like this, and it will store the data in your useState()
.您可以像这样显示它,它会将数据存储在您的
useState()
中。 I've created that formattedData
to recreate your object我已经创建了
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.