先谢了。我使用axios.get()获取后端数据,但是对象数组没有填充状态
它在控制台中给我以下。Outside Effect {success: true, message: 'All Categories List', category: Array(2)} [] Outside Effect[object Object],[object Object]
后端代码也给出了。
const [categories,setCategories] =useState([])
const getAllCategory = async () => {
try {
const {data} = await axios.get("/api/v1/category/get-category");
if (data.success) {
console.log(data)
setCategories(data.category);
console.log(categories)
}
} catch (error) {
console.log(error);
toast.error("Something `enter code here`went wrong in getting category");
}
};
useEffect(() => {
getAllCategory();
}, []);
console.log("Outside Effect"+categories)
//后端代码
export const categoryController = async (req, res) => {
try {
const category = await categoryModel.find({});
res.status(200).send({
success: true,
message: "All Categories List",
category,
});
} catch (error) {
console.log(error);
res.status(500).send({
success: false,
message: "Error While Getting All Categories",
error,
});
}
};
2条答案
按热度按时间yyhrrdl81#
其他的输入错误,setState下面的console.log(categories)将不会显示更新的类别,因为setState是异步进程。你可以为那个添加一个使用效果->
qncylg1j2#
给予这个: