我是React的新手,出现此错误:
`对象无效,不能作为React子对象(找到:带有键{}的对象)。如果要渲染子级集合,请改用数组。'
当我尝试通过从数组映射它们来呈现组件的集合时。
我已经阅读了许多有关此主题的主题,但是我无法弄清楚这段代码有什么问题。
谢谢!
function ItemPage({items}) {
return (
<ul>
{
items.map((item) =>
<li key={item.id}>
<Item title={item.name} />
</li>
)
}
</ul>
);
}
这是项数组:
let items = [{
id: 0,
name: "Apple iPad Mini 2 16GB",
description: "An iPad like no other. 16GB, WiFi, 4G.",
price: 229.00
}, {
id: 1,
name: "Apple iPad Mini 2 32GB",
description: "Even larger than the 16GB.",
price: 279.00
}, {
id: 2,
name: "Canon T7i",
description: "DSLR camera with lots of megapixels.",
price: 749.99
}, {
id: 3,
name: "Apple Watch Sport",
description: "A watch",
price: 249.99
}, {
id: 4,
name: "Apple Watch Silver",
description: "A more expensive watch",
price: 599.99
}
];
答案 0 :(得分:0)
该错误不在您发布的代码中。运行下面的代码片段以查看代码的功能。我添加的唯一没有添加到您的代码中的是<Item/>
组件的定义,所以也许就是您的问题所在。
function Item({title}){
return (<span>{title}</span>);
}
function ItemPage({items}) {
return (
<ul>
{
items.map((item) =>
<li key={item.id}>
<Item title={item.name} />
</li>
)
}
</ul>
);
}
let items = [{
id: 0,
name: "Apple iPad Mini 2 16GB",
description: "An iPad like no other. 16GB, WiFi, 4G.",
price: 229.00
}, {
id: 1,
name: "Apple iPad Mini 2 32GB",
description: "Even larger than the 16GB.",
price: 279.00
}, {
id: 2,
name: "Canon T7i",
description: "DSLR camera with lots of megapixels.",
price: 749.99
}, {
id: 3,
name: "Apple Watch Sport",
description: "A watch",
price: 249.99
}, {
id: 4,
name: "Apple Watch Silver",
description: "A more expensive watch",
price: 599.99
}
];
ReactDOM.render(
<ItemPage items={items}/>,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="react"></div>
答案 1 :(得分:0)
我只是想出我的代码出了什么问题,问题不在组件'ItemPage'的定义中,而是在Item的定义中
我有以下
array_merge_recursive
我更改了仅用于道具的函数的参数,并且效果很好。
const Item = (props,children) =>{
return (
<div className="item">
<div className="left">
<ItemImage/>
<div className="imageDescription">
<ItemTitle title={props.title}/>
<ItemDescription description={props.description}/>
</div>
</div>
<div className="right">
<ItemPrice price={props.price}/>
{children}
</div>
</div>
);}