首页 > 解决方案 > 我无法访问 JS 中的对象键

问题描述

在从父组件接收道具的反应组件中工作。道具是静态的(无需检查更新)并且接收正常。prop 是一个对象数组。该数组在控制台中记录正常,即使单个数组项数组 [x] 也已正确记录到控制台,但是如果我想访问特定键(例如“eventDate”),它会记录“无法读取未定义的事件日期” .

import React, { Component } from 'react';

// AUX COMP
import Moment from 'react-moment'; // --> https://momentjs.com/
import moment from 'moment';

// SERVICE API
import Calculations from '../../services/Calculations';


export default class EventsGraphic extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      user              : this.props.userID,
      patientId         : this.props.patID,

      patientsEvents    : this.props.events,
      eventsSorted      : [],
      firstEventDate    : '',

      timeLineDays      : 60,
    }
  }

_eventsGraphicData(){

   let pEvts = [...this.props.events];
   let eventsSorted  = Calculations.sortByEventDate(pEvts); 

    console.log('pEvts', pEvts);
    console.log('eventsSorted[0]', eventsSorted[0]);
        // this prints to the console the object in the index 0 of the array correctly ONE OF THE KEYS IS eventDate
        console.log('eventsSorted[0].eventDate = ', eventsSorted[0].eventDate);
       // THIS LOGS "CAN NOT READ PROPERTY eventDate OF UNDEFINED ?!?!?!


return eventsSorted

  }

render() {

  return (


  <div className="events-chart">

    <p>DATA GOES HERE</p>

  </div>


   );
 };
};

在此处输入图像描述

在此处输入图像描述

标签: javascriptreactjsobjectkey

解决方案


您在 sortedEvent 而不是 Object 中有 Stringified 对象,当然在键上收到 undefined 。


推荐阅读