React render:对象作为React子对象无效 [英] React render: Objects are not valid as a React child
问题描述
请帮帮我。我不知道为什么这段代码不起作用。
Please help me. I don't know why this piece of code doesn't work.
它给了我一个错误:对象作为React子句无效(找到:对象与keys {itemss})。如果你想渲染一个子集合,请改用数组。
为什么{i.title}是一个对象。这只是一个字符串。我怎样才能解决这个问题?我实际上可以迭代嵌套对象吗?
It gives me an error: "Objects are not valid as a React child (found: object with keys {itemss}). If you meant to render a collection of children, use an array instead." Why {i.title} is an object. It's just a string. How can i fix this? and How actually I can iterate nested objects?
class ShopItem extends React.Component {
render() {
var items = [
{
link: 'first link',
title: 'Emery NEM XF',
price: '$950'
},
{
link: 'second link',
title: 'Emery NEM XF',
price: '$950'
},
{
link: 'third link',
title: 'Emery NEM XF',
price: '$950'
}
];
const item = items.map((i) =>{
return ( <h1>{i.title}</h1> )
});
return (
{items}
)
}
}
ReactDOM.render(<ShopItem /> , document.querySelector('#root'));
推荐答案
问题是因为你退货
return (
{items}
)
相当于 return({items:items})
ie。您将返回一个对象,其中包含键 items
和 React不希望渲染对象
。你可以写
which is an equivalent of return ({items: items})
ie. you are returning an object with key items
and React doesn't expect objects for rendering
. You could either write
const items = items.map((i) =>{
return ( <h1>{i.title}</h1> )
});
return items;
或
return items.map((i) =>{
return ( <h1>{i.title}</h1> )
});
或
const items = items.map((i) =>{
return ( <h1>{i.title}</h1> )
});
return <React.Fragment>
{items}
</React.Fragment>
P.S。请注意,前两种方法可以从
反应v16.0.0
,而最后一种方法可以从
开始v16.2 $ c开始工作$ c>以后。
P.S. Note that the first two approaches will work from
react v16.0.0 onwards
while the last will work fromv16.2
onwards.
但是如果你使用的是较低版本,你需要将return元素包装在像<的容器中/ p>
However if you are using a lower version, you would need to wrap the return element within a container like
return (
<div>{items}</div>
)
这篇关于React render:对象作为React子对象无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!