首页 > 解决方案 > 对象的问题 - 不会映射

问题描述

每当我运行我的 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

标签: javascriptarraysreactjsjavascript-objects

解决方案


因为 React 组件必须呈现单个根元素,所以您需要将其包装在片段或元素中:

return (
  <>{ mappedCats }</>
)

作为原始 js(未包含在标记中),您的渲染方法返回一个对象文字:

// this is shorthand for { mappedCats: mappedCats }
return { mappedCats };

推荐阅读