【问题标题】:Cannot read property 'name' of undefined on React with my props无法使用我的道具在 React 上读取未定义的属性“名称”
【发布时间】:2025-12-16 17:20:03
【问题描述】:

我正在尝试使用 getVehicleByUser 操作读取一些数据,正如您在图片中看到的那样,我的控制台日志中显示了我的道具,但在 [0].name 之后无法读取我的数据。我知道我的第一个控制台日志是空的 {} 并且在另外两个之后他给了我两倍的数据结果。如果有人现在是怎么回事?我在 app.js<Route exact path="/user/:id" component={UserShow}/> 中也使用了 react-router-dom


import React from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import * as actions from "../actions";

class UserShow extends React.Component {
  componentDidMount(){
    this.props.getVehicleByUser(this.props.match.params.id);
  }

  renderListVehicle(){
      console.log(this.props.vehicles); // Work
      console.log(this.props.vehicles[0]); //Work
      // console.log(this.props.vehicles[0].name) DON'T WORK ?????
  }

  render() { 
    return (
      <div className="container">
        <div className="row">
          <div className="col s12 m6">
            <div className="card">
                  {this.renderListVehicle()}
            </div>
          </div>
        </div>
      </div>
    );
  }
}

function mapStateToPros(state) {
  return {
    authenticated: state.auth.authenticated,
    vehicles: state.vehicles
  };
}

export default connect(mapStateToPros, actions)(UserShow);


减速器



export default function(state = {}, action){
    switch (action.type) {
        case GET_MY_VEHICLE:
            return action.payload || false;
        default:
            return state
    }
}```

【问题讨论】:

  • 您的初始状态如何?还有减速器

标签: reactjs mongoose redux


【解决方案1】:

这没有按预期工作,因为您要查找的道具尚未填充。它正在加载页面,然后在 componentDidMount 上向父元素发送回调以收集更多信息并继续发送。

我建议先检查车辆数据是否存在,然后继续执行其余功能。您甚至可以在此页面中添加一个加载元素,以便在您收集他们的特定信息时向用户显示。

您可以做的另一件事(单独或与上述一起)是destructure 车辆数据并为其提供默认道具,以便您的功能不会中断。

【讨论】:

  • 如果我这样做就不起作用:renderListVehicle(){ if(this.props.vehicles){ console.log(this.props.vehicles[0].name) } }'Cannot read property 'name' of undefined'
  • 您的语法只有在您没有将任何值作为车辆属性传递给组件或该值为空时才有效。如果你将一个空数组传递给组件,你会做类似if(this.props.vehicles.length &gt; 0){...}.
  • 感谢先生@technicallynick
【解决方案2】:

我认为问题在于 store 道具还没有在最高峰。(说道具还没有我的意思是数据还没有填充) 试试这个:

if(this.props.vehicles[0].name){ 
  console.log(this.props.vehicles[0].name)
}

【讨论】:

    最近更新 更多