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

React报错:Cannot read property 'name' of undefined原因咨询

解决React中"Cannot read property 'name' of undefined"的问题

Hey there! Let's break down why you're running into this error and fix it step by step.

错误原因分析

The Cannot read property 'name' of undefined error tells us that when you try to access .name on this.props.users, this.props.users is actually undefined—meaning your component isn't receiving the user data you think it is.

Looking at your UserItem component, it's designed to render info for a single user, so the issue is almost certainly a mismatch in how you're passing or accessing props.

常见的问题场景及修复方案

Here are the two most likely scenarios:

  1. Props名称不匹配
    If your parent component is passing a single user object with the prop name user (like this):

    // 父组件中的代码示例
    <UserItem user={mySingleUserObject} />
    

    But your UserItem is trying to access this.props.users (plural), that's why this.props.users is undefined. You need to use the same prop name in both places.

  2. 直接传递了数组而非单个用户
    If your parent component has an array of users, you can't pass the entire array directly to UserItem. You need to loop through the array and pass each individual user to a separate UserItem component. For example:

    // 父组件中的正确写法
    {this.state.users.map(user => (
      <UserItem key={user.id} user={user} />
    ))}
    

    The key prop is required here to help React track list items efficiently.

修正后的UserItem组件

Here's a cleaned-up version of your component that fixes the issue and adds a safety check to avoid similar errors in the future:

import React, { Component } from "react";

class UserItem extends Component {
  render() {
    // 解构props,让代码更清晰
    const { user } = this.props;
    
    // 安全检查:如果user未定义,就不渲染内容
    if (!user) {
      return null;
    }

    return (
      <li className="UserLI">
        {user.name} is {user.age} years old.
      </li>
    );
  }
}

export default UserItem;

额外排查技巧

  • Add console.log(this.props) at the top of your render method to see exactly what props your component is receiving. This will help you confirm if the data is coming through correctly.
  • Double-check that the user objects you're passing actually have name and age properties—sometimes typos in object keys can cause similar issues too!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:57:20