You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用forEach传递props后组件无渲染问题排查

React组件渲染集合无内容问题排查

我正在学习FullstackOpen 2023课程,在第二部分作业中需渲染集合,App.jsx代码如下:

import Course from './components/Course'

const App = () => {
  const course = 'Half Stack application development'
  const parts = [
    {
      name: 'Fundamentals of React',
      exercises: 10
    },
    {
      name: 'Using props to pass data',
      exercises: 7
    },
    {
      name: 'State of a component',
      exercises: 14
    }
  ] 

  return (    
    <div>
      <Course header={course} content={parts} />
    </div>
  )
}
export default App

我尝试将parts数组传递给Course组件,用forEach渲染其属性,Course.jsx代码如下:

const Part = ({ part }) => {

    <p>
        {part.name} {part.exercises}
    </p>

}

const Course = ({ header, content }) => {

    <h1>{header}</h1>

    content.forEach(x => {        
        <Part part={x}
         />
    })
}

export default Course

但浏览器无任何内容显示,改用map()也无效。调试时在forEach中加入console.log(x),控制台能正常输出数据,却仍无法渲染组件。请问这是为什么?


编辑补充:总结的经验

  • 每个组件都必须有Return语句
  • 箭头函数写法关键:使用=> { }时无隐式返回,需显式写=> { return ( ) };使用=> ()时,括号内内容会被隐式返回
  • map需要返回语句,map (x => {} )和map (x => () )不等价

抱歉这是新手问题,我刚学React,解构语法虽好用但仍有困惑。


内容的提问来源于stack exchange,提问作者JulianGR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 16:13:43