【发布时间】:2021-11-04 20:08:06
【问题描述】:
我有类别,每个类别都有子类别,我想 setState 像一个字典
{category1.name: [/*list of all subcategories*/], category2.name: [...]}
我有
useEffect(()=>{
Axios.get("http://localhost:3001/categories/get").then((p) => { /* return a list of categories */
setCategories(p.data)
let actual = {}
for (let i = 0; i < p.data.length; i++) {
Axios.get("http://localhost:3001/category/subcategories", { /* return all the subcategories of p.data[i], this is working! */
params : {category : p.data[i].category}}).then((p) => {
actual = {...actual, [p.data[i].category]: p.data}
console.log(actual) /* 1 */
})
}
console.log(actual) /* 2 */
})
}, [])
我已经让后端工作了,但是当我 console.log(actual) /* 2 */ 它只是一个空字典 {};当我console.log(actual) /* 1 */ 不是空的(只有 1 个元素),我不知道我什么时候可以setState(actual),有人知道我想要做什么吗?
【问题讨论】:
-
这里你需要使用promise,作为你的第二个控制台,即
console.log(actual) /* 2 */在第一个控制台之前执行。所以它打印一个空对象。
标签: node.js reactjs use-effect setstate