javascript - 对象的问题 - 不会映射
问题描述
每当我运行我的 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 组件只是获取道具并将它们放入 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 };
推荐阅读
- javascript - Request.ServerVariables.Keys 返回空
- svg - 如何使用 groovy 字符串替换或 XML Parser 来编辑 SVG 字符串
- c# - C# 将自动 IP 关联更改为手动 IP 集
- excel - 如何按顺序对多列进行排序并使行合并为相同的值?
- c - 如何设置 SUID 位以授予 root 权限?
- security - AbpAuditlogs 中记录了哪些可疑活动?他们的意图是什么?
- laravel-livewire - Livewire 按钮不会点击
- neo4j - 根据 graphQL 模式验证 neo4j 数据库
- vue.js - Vue.js:配置 Router.js 后出错。Vue/类型/umd。chokidar(C 驱动器错误)
- python - SSLContext 超过最大递归深度(eventlet、flask、flask-socketio、tweepy)