[英]How to fix error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead
I'm trying to set the a state with an array of objects but I'm getting the above error and I do not know how to resolve it.我正在尝试使用一组对象设置 a 状态,但出现上述错误,我不知道如何解决它。
My code:我的代码:
const [itemsInCart, setItemsInCart] = useState([]);
useEffect(() => {
const fetchData = async () => {
await fetch("https://fakestoreapi.com/products?limit=16")
.then((res) => res.json())
.then((data) => {
const initialItemCount = data.map((item) => {
return {
name: item.title,
qty: 0,
};
});
setItemsInCart(initialItemCount);
});
};
fetchData();
}, []);
I tried console.log(Array.isArray(initialItemCount))
to check if it is an array and it returned true.我尝试
console.log(Array.isArray(initialItemCount))
来检查它是否是一个数组并且它返回了 true。 So why is it saying to use an array?那么为什么说使用数组呢? Thank you
谢谢
You can use a breakpoint to see the final value of itemsInCart
, to check if this array contains the list of React child component.您可以使用断点查看
itemsInCart
的最终值,以检查此数组是否包含 React 子组件的列表。
From your code, I guess the array only contains the object of {name and qty}, which can not be rendered directly.从您的代码中,我猜该数组仅包含 {name and qty} 的对象,无法直接呈现。
You may try parsing these objects to a component to render UI.您可以尝试将这些对象解析为组件以呈现 UI。
Hope this help.希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.