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

React项目解构Props时触发Cannot read property 'map' of undefined错误求助

Fixing "Cannot read property 'map' of undefined" for languages in JobCard Component

Looks like you're hitting a common issue where one of your job entries doesn't have the languages property (check the second entry in your JSON—it only has tools!), and when your JobCard tries to call map on an undefined value, it throws that error. Let's break down the fixes step by step:

1. Add a Default Value for the languages Prop

The simplest fix is to assign an empty array as the default value when destructuring the languages prop. This ensures even if a job doesn't have the languages field, you'll always have an array to call map on:

const JobCard = ({
  company, 
  position, 
  postedAt, 
  contract, 
  location, 
  logo, 
  featured, 
  new: newJob, 
  languages = [] // Default to empty array
}) => (
  // Rest of your component code...
)

2. Use Optional Chaining to Guard Against Undefined

Another approach is to use JavaScript's optional chain operator (?.) to only run map if languages exists and is not null/undefined:

{languages?.map((language) => <CustomButton>{language}</CustomButton> )}

This is a quick one-line fix that prevents the error without altering the prop defaults.

3. Include tools in Your Buttons (Bonus!)

Since your second job entry has a tools array instead of languages, you probably want to render those as buttons too. Here's how you can combine both arrays and render all tags:

const JobCard = ({
  company, 
  position, 
  postedAt, 
  contract, 
  location, 
  logo, 
  featured, 
  new: newJob, 
  languages = [],
  tools = [] // Add default for tools too
}) => {
  // Combine languages and tools into one array
  const allSkillTags = [...languages, ...tools];

  return (
    <div className="container">
      <div className='card'>
        {/* Rest of your component content... */}
        {allSkillTags.map((tag, index) => (
          <CustomButton key={index}>{tag}</CustomButton>
        ))}
      </div>
    </div>
  )
}

Note: Using index as the key is acceptable here since the order of tags won't change dynamically, but if you ever have duplicate tags and need unique keys, you could combine the tag with the job's id (pass id to JobCard first) like key={${id}-${tag}}.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 18:07:53