gpt4 book ai didi

javascript - react 渲染 : Objects are not valid as a React child

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:57:52 24 4
gpt4 key购买 nike

请帮帮我。我不知道为什么这段代码不起作用。

它给了我一个错误:“对象作为 React 子项无效(已找到:具有键 {itemss} 的对象)。如果您打算渲染子项集合,请改用数组。” 为什么 {i.title} 是一个对象。它只是一个字符串。我怎样才能解决这个问题?以及我实际上如何迭代嵌套对象?

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}) 即。您正在返回一个包含键 items 的对象,并且 React 不期望渲染对象。你可以写

   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. Note that the first two approaches will work from react v16.0.0
onwards
while the last will work from v16.2 onwards.

但是,如果您使用的是较低版本,则需要将返回元素包装在类似

的容器中
    return (
<div>{items}</div>
)

关于javascript - react 渲染 : Objects are not valid as a React child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50230912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com