[英]Issues with an object- Will not map
每当我运行 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。 然后遍历该类别的项目以显示每个项目的名称和成本。 我尝试将对象转换为数组,但它似乎不起作用。 最初我尝试将其拆分为多个组件,但我认为我过于雄心勃勃。
Categories 组件只是获取 props 并将它们放入一个 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 组件必须渲染单个根元素,因此您需要将其包装在片段或元素中:
return (
<>{ mappedCats }</>
)
作为原始 js(未包含在标记中),您的渲染方法正在返回一个对象文字:
// 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.