【发布时间】:2022-01-26 18:46:58
【问题描述】:
我正在尝试在 reactjs 中呈现来自 Axios 的响应。响应是来自 MySQL 数据库的数据。请在下面查看我的代码并收到错误消息Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead. 我将不胜感激。谢谢。
const Products = () => {
const fd = () => {
return Axios.get("http://localhost:5000/popular-products")
.then(response => response.data)
}
return (
<Container>
{fd().then((data) => {
data.map((item)=>(
<h1>{item.prod_name}</h1>
))
})}
</Container>
);
};
export default Products;
【问题讨论】:
-
你正试图在 JSX 中解决承诺。在该函数 (fd) 中执行所有操作并获取最终数据。使用 useState 并使用最终数据设置状态,然后映射列表并返回 JSX。
-
我试过useState,但是axios响应加载了多次
-
“多次加载”是什么意思?
-
@MattU 是的,它回答了我的问题。感谢您的帮助。