问题描述
每当我运行React程序时,都会出现以下错误:
Objects are not valid as a React child (found: object with keys {mappedCats}). If you meant to render a collection of children,use an array instead.
in choicesList (at App.js:33)
我想做的是获取FEATURES对象,对其进行迭代,并为每个类别创建一个div。然后遍历该类别的项目以显示每个项目的名称和成本。我尝试将对象转换为数组,但似乎无法正常工作。最初,我试图将其分解为多个部分,但我认为自己过于雄心勃勃。
类别组件仅获取道具并将它们放入div和段落中。
如果有人可以指出我的错误,我将不胜感激。谢谢
import React from 'react'
import Categories from './categories'
const choicesList = (props) => {
const FEATURES = {
Processor: [
{
name: '17th Generation Intel Core HB (7 Core with donut spare)',cost: 700
},{
name: 'Professor X AMD Fire Breather with sidewinder technology',cost: 1200
}
],"Operating System": [
{
name: 'Ubuntu Linux 16.04',cost: 200
},{
name: 'Bodhi Linux',cost: 300
}
],"Video Card": [
{
name: 'Toyota Corolla 1.5v',cost: 1150.98
},{
name: 'Mind mild breeze 2000',cost: 1345
}
],display: [
{
name: '15.6" UHD (3840 x 2160) 60Hz Bright Lights and Knobs',cost: 1500
},{
name: '15.3" HGTV (3840 x 2160) Home makeover edition',cost: 1400
},]
};
const mappedCats = Object.keys(FEATURES).map((cat) => {
return (
<div>
<h1>{cat}</h1>
{Object.keys(FEATURES[cat]).map((item,idx) => {
return (
<Categories name={FEATURES[cat][idx].name} cost={FEATURES[cat][idx].cost}/>
)
})}
</div>
)
})
return(
{mappedCats}
)
}
export default choicesList
解决方法
由于React组件必须呈现单个根元素,因此您需要将其包装在fragment或元素中:
return (
<>{ mappedCats }</>
)
作为原始js(未包含在标记中),您的render方法将返回对象文字:
// this is shorthand for { mappedCats: mappedCats }
return { mappedCats };
,
mappedCats
本身是有效的元素。只需退还
return mappedCats
const ChoicesList = (props) => {
const FEATURES = {
Processor: [
{
name: "17th Generation Intel Core HB (7 Core with donut spare)",cost: 700,},{
name: "Professor X AMD Fire Breather with sidewinder technology",cost: 1200,],"Operating System": [
{
name: "Ubuntu Linux 16.04",cost: 200,{
name: "Bodhi Linux",cost: 300,"Video Card": [
{
name: "Toyota Corolla 1.5v",cost: 1150.98,{
name: "Mind mild breeze 2000",cost: 1345,Display: [
{
name: '15.6" UHD (3840 x 2160) 60Hz Bright Lights and Knobs',cost: 1500,{
name: '15.3" HGTV (3840 x 2160) Home makeover edition',cost: 1400,};
const mappedCats = Object.keys(FEATURES).map((cat) => {
return (
<div>
<h1>{cat}</h1>
{Object.keys(FEATURES[cat]).map((item,idx) => {
return (
<div>
{`name: ${FEATURES[cat][idx].name}`}
<br></br>
{`cost: ${FEATURES[cat][idx].cost}`}
</div>
);
})}
</div>
);
});
return mappedCats;
//return (<div>{ mappedCats }</div>);
};
const domContainer = document.querySelector('#app');
ReactDOM.render(<ChoicesList />,domContainer);
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="app"> </div>