简体   繁体   中英

Accessing nested JSON data with React Hooks & Props

I'm trying to access data further down into my JSON file. I am able to easily access data in the first two data sets in rows and area :

data.json

"rows": [
    {
      "uid":"001",
      "type": "Lorem ipsum",

      "area": [
        {

          "name": "London",
          "number": "12345",

          "wait": {
            "start": {
              "start_time": 1585129140,
              "delay": 300
            },
            "end": {
              "end_time": 1585130100,
              "delay": 300
            }
          },
          "in": 1585129140,
          "out": 1585130100,
        },

However when I try to access the data under wait which includes this block:

          "wait": {
            "start": {
              "start_time": 1585129140,
              "delay": 300
            },
            "end": {
              "end_time": 1585130100,
              "delay": 300
            }
          },

No data is getting returned on screen from my jsx file, but it is available in the console log

TimeTracker.jsx

const TimeTracker = (props) => {

  const trainTime = useState(props.data);
  console.log(props.data);
  
  
  return (
    <>
      <div className={style.timeLabel}>
      <div className={style.startTime}>{trainTime.start_time}</div>
      <div className={style.endTime}></div>
      </div>
    </>
    )
  };
  export default TimeTracker;

console.log

wait:
start:
start_time: 1585129140
delay: 300
__proto__: Object
end:
end_time: 1585130100
delay: 300
__proto__: Object
__proto__: Object

I've used the same pattern for passing props in other components and it works fine on the first two levels so I don't understand why it's not working. How do I get data from further in this JSON?

useState returns a tuple with the object and a function to set the value on the object. You probably need to change your component to something like this:

const TimeTracker = (props) => {

  const [trainTime, setTrainTime] = useState(props.data);
  console.log(props.data);


  return (
    <>
      <div className={style.timeLabel}>
      <div className={style.startTime}>{trainTime.start_time}</div>
      <div className={style.endTime}></div>
      </div>
    </>
    )
  };
  export default TimeTracker;

A nested property can not be accessed by one level of ab so instead of

<div className={style.startTime}>{trainTime.start_time}</div>

it should be

<div className={style.startTime}>{trainTime.wait.start.start_time}</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM