[英]How to save and display data retrieved from database
So I've retrieved data in JSON
format using GET
request then I'm facing a problem in saving into my state
so that I can display them into my span
/ div
/ h1
using map function
. So I've retrieved data in
JSON
format using GET
request then I'm facing a problem in saving into my state
so that I can display them into my span
/ div
/ h1
using map function
. Here's how my JSON
data looks like:这是我的
JSON
数据的样子:
[
{
"projectName": "SHIBA INU",
"projectToken": "SHIB",
"tokenPrice": 0.2,
"saleStart":{
"$date": "2021-12-20T20:00:00.00Z"
},
{
"projectName": "BITCOIN",
"projectToken": "BTC",
"tokenPrice": 200,
"saleStart":{
"$date": "2021-12-20T20:00:00.00Z"
}
]
So I'm trying to do this way but I dont think it will work:所以我正在尝试这样做,但我认为它不会起作用:
const [projectData, setProjectData] = useState({})
useEffect(() => {
axios.get(`my api`).then(res => {
for(let i=0; i<res.data.length; i+1){
setProjectData(...projectData, res.data[i])
}
}).catch(e => console.log("error: ", e));
},[]);
I'm not sure whether I should save them into an array or an object我不确定是否应该将它们保存到数组或 object
From the data in your example, it seems like you're trying to store an array of objects, so you'll want to initialize your state with an array, and then add the items from the response to the array as well.从示例中的数据来看,您似乎正在尝试存储对象数组,因此您需要使用数组初始化 state,然后将响应中的项目也添加到数组中。 You also don't need the loop: you can spread all of the array items into a new array along with the existing state in one step:
您也不需要循环:您可以一步将所有数组项与现有 state 一起传播到一个新数组中:
const [projectData, setProjectData] = useState([]);
useEffect(() => {
axios.get(`my api`).then(res => {
setProjectData([...projectData, ...res.data]);
}).catch(e => console.log("error: ", e));
}, []);
First of all you are not updating your i
value in your for loop.首先,您没有在 for 循环中更新
i
值。 Since your i
value never will be less than res.data.length, it will loop infinitely.由于您的
i
值永远不会小于 res.data.length,因此它将无限循环。 Instead you should use i++
to increment it at each iteration:相反,您应该使用
i++
在每次迭代时递增它:
for(let i=0; i<res.data.length; i++)
Other than that setting your state like that is problematic.除了像这样设置你的 state 是有问题的。
setState
in React is async which means when you use it and access your projectData
it won't promise you that you are getting the updated state right away. React 中的
setState
是异步的,这意味着当您使用它并访问您的projectData
时,它不会 promise 您立即获得更新的 state。 Instead you should try to update your state at once in your case.相反,您应该尝试在您的情况下立即更新您的 state。 Also check Why is setState in reactjs Async instead of Sync?
还要检查为什么 reactjs 中的 setState 是异步而不是同步?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.