【问题标题】:Rendering nested json data in react js在 React js 中渲染嵌套的 json 数据
【发布时间】:2020-07-02 12:51:18
【问题描述】:

我正在尝试渲染和显示嵌套的 json 数据,但我有一些问题,这是代码。

import React, { useState, useEffect, useRef } from "react";
//import Moment from 'react-moment';
//import 'moment-timezone';
import moment from 'moment';


const dueTimes = [
  {
    distance: 6113,
    start: {
      time: moment().format("2020 7 1, 14, 38, 9"),
      address: "University College Dublin, Belfield, Dublin 4, Ireland",
      location: { lat: 53.30713120000001, lng: -6.220312 }
    },
    end: {
      time: moment().format("2020 7 1, 15, 2, 8"),
      address: "College Green, Dublin 2, Ireland",
      location: { lat: 53.3443633, lng: -6.2593112 }
    },
    steps: [
      {
        distance: 347,
        duration: 244,
        start: { lat: 53.30713120000001, lng: -6.220312 },
        stop: { lat: 53.309375, lng: -6.2187873 },
        mode: "WALKING"
      },
      {
        distance: 5445,
        duration: 968,
        start: { lat: 53.3094124, lng: -6.218878399999999 },
        stop: { lat: 53.3404818, lng: -6.2585706 },
        mode: "TRANSIT",
        transit: {
          dep: {
            name: "UCD N11 Entrance, stop 768",
            time: moment().format("2020 7 1, 14, 42, 13")
          },
          arr: {
            name: "Dawson Street, stop 792",
            time: moment().format("2020 7 1, 14, 58, 21")
          },
          headsign: "Ongar",
          type: "Dublin Bus",
          route: "39a"
        }
      },
      {
        distance: 321,
        duration: 226,
        start: { lat: 53.34212669999999, lng: -6.258003599999999 },
        stop: { lat: 53.3443633, lng: -6.2593112 },
        mode: "WALKING"
      }
    ]
  }
];

function Routes() {
    return (
        <div className="App">
            <div className="posts">
                {dueTimes.map(item => {
                    return (
                        <>
                            <h4>{item.distance}</h4>
                            <p>{item.start.time} </p>
                        </>

                    )
                })}
            </div>
        </div>
    );
}

export default Routes;

如何渲染所有这些数据 - 我也尝试添加嵌套地图,但似乎无法让它工作。是的,我试图显示所有这些数据。当我尝试访问嵌套数据时,我得到“错误:对象作为 React 子级无效(找到:带有键 {lat,lng} 的对象)。如果您打算渲染一组子级,请改用数组。”

【问题讨论】:

标签: javascript json reactjs


【解决方案1】:
import * as React from "react";
import "./styles.css";
import moment from "moment";

const dueTimes = [
  {
    distance: 6113,
    start: {
      time: moment().format("2020 7 1, 14, 38, 9"),
      address: "University College Dublin, Belfield, Dublin 4, Ireland",
      location: {
        lat: 53.30713120000001,
        lng: -6.220312
      }
    },
    end: {
      time: moment().format("2020 7 1, 15, 2, 8"),
      address: "College Green, Dublin 2, Ireland",
      location: {
        lat: 53.3443633,
        lng: -6.2593112
      }
    },
    steps: [
      {
        distance: 347,
        duration: 244,
        start: {
          lat: 53.30713120000001,
          lng: -6.220312
        },
        stop: {
          lat: 53.309375,
          lng: -6.2187873
        },
        mode: "WALKING"
      },
      {
        distance: 5445,
        duration: 968,
        start: {
          lat: 53.3094124,
          lng: -6.218878399999999
        },
        stop: {
          lat: 53.3404818,
          lng: -6.2585706
        },
        mode: "TRANSIT",
        transit: {
          dep: {
            name: "UCD N11 Entrance, stop 768",
            time: moment().format("2020 7 1, 14, 42, 13")
          },
          arr: {
            name: "Dawson Street, stop 792",
            time: moment().format("2020 7 1, 14, 58, 21")
          },
          headsign: "Ongar",
          type: "Dublin Bus",
          route: "39a"
        }
      },
      {
        distance: 321,
        duration: 226,
        start: {
          lat: 53.34212669999999,
          lng: -6.258003599999999
        },
        stop: {
          lat: 53.3443633,
          lng: -6.2593112
        },
        mode: "WALKING"
      }
    ]
  }
];

export default function App() {
  return (
    <div className="App">
      <h1>Hello React Object Output</h1>
      {dueTimes.map(item => {
        return (
          <>
            <h4>Distance : {item.distance}</h4>
            <div>
              <h3>Start </h3>
              <p>Start Time: {item.start.time} </p>
              <p>Start address: {item.start.address} </p>
              <p>
                Start location: {item.start.location.lat} -{" "}
                {item.start.location.lng}{" "}
              </p>
            </div>
            <div>
              <h3>End </h3>
              <p>Start Time: {item.end.time} </p>
              <p>Start address: {item.end.address} </p>
              <p>
                Start location: {item.end.location.lat} -{" "}
                {item.end.location.lng}{" "}
              </p>
            </div>
            <div>
              <h3>steps </h3>
              <div>
                {item.steps.map((step, i) => {
                  return (
                    <div key={i}>
                      <p>Step mode: {step.mode}</p>
                      <p>Step Distance: {step.distance}</p>
                      <p>Step duration: {step.duration}</p>
                      {step.transit && (
                        <div>
                          <h5 style={{ background: "red", color: "white" }}>Transit</h5>
                          <p style={{ background: "yellow", color: "black" }}>Route: {step.transit?.route}</p>
                          <p style={{ background: "yellow", color: "black" }}>Type: {step.transit?.type}</p>
                          <p style={{ background: "yellow", color: "black" }}>headsign: {step.transit?.headsign}</p>
                          <p style={{ background: "yellow", color: "black" }}>dep.name: {step.transit?.dep.name}</p>
                          <p style={{ background: "yellow", color: "black" }}>dep.time: {step.transit?.dep.time}</p>
                          <p style={{ background: "yellow", color: "black" }}>arr.name: {step.transit?.arr.name}</p>
                          <p style={{ background: "yellow", color: "black" }}>arr.time: {step.transit?.arr.time}</p>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          </>
        );
      })}
    </div>
  );
}

https://codesandbox.io/s/async-rgb-nhmvy?file=/src/App.tsx:0-4119

这里是怎么做的。

您需要查找每个数组或对象并再次迭代

【讨论】:

  • 嘿@Danish 谢谢它的工作,现在更有意义了!只是上面的几个问题。第二次映射迭代中的参数'i'和键值i有什么用。另外,为什么您有“{step.transitt &&”,它会检查传输对象中是否存在值以及是否存在渲染内容?
  • 嗨@overblast {step.transitt && ()} 这是条件渲染,因为现在所有步骤都没有传输键。第二个映射中的第二个参数“i”是关键,Keys help React identify which items have changed, are added, or are removedreactjs.org/docs/lists-and-keys.html#keys 请也将密钥应用到第一张地图,我错过了 :)
【解决方案2】:
const people = [
  {
    name: 'Mike Smith',
    family: {
      mother: 'Jane Smith',
      father: 'Harry Smith',
      sister: 'Samantha Smith'
    },
    age: 35
  },
  {
    name: 'Tom Jones',
    family: {
      mother: 'Norah Jones',
      father: 'Richard Jones',
      brother: 'Howard Jones'
    },
    age: 25
  }
];

for (const {name: n, family: {father: f}} of people) {
  console.log('Name: ' + n + ', Father: ' + f);
}

// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"

尝试在此处阅读有关分解的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment 它帮助了我。

【讨论】:

    【解决方案3】:

    如果我的问题没有正确,您想知道如何映射一些嵌套数据。

    import React, { Fragment } from "react";
    import moment from "moment";
    
    const dueTimes = [
      {
        distance: 6113,
        start: {
          time: moment().format("2020 7 1, 14, 38, 9"),
          address: "University College Dublin, Belfield, Dublin 4, Ireland",
          location: { lat: 53.30713120000001, lng: -6.220312 }
        },
        end: {
          time: moment().format("2020 7 1, 15, 2, 8"),
          address: "College Green, Dublin 2, Ireland",
          location: { lat: 53.3443633, lng: -6.2593112 }
        },
        steps: [
          {
            distance: 347,
            duration: 244,
            start: { lat: 53.30713120000001, lng: -6.220312 },
            stop: { lat: 53.309375, lng: -6.2187873 },
            mode: "WALKING"
          },
          {
            distance: 5445,
            duration: 968,
            start: { lat: 53.3094124, lng: -6.218878399999999 },
            stop: { lat: 53.3404818, lng: -6.2585706 },
            mode: "TRANSIT",
            transit: {
              dep: {
                name: "UCD N11 Entrance, stop 768",
                time: moment().format("2020 7 1, 14, 42, 13")
              },
              arr: {
                name: "Dawson Street, stop 792",
                time: moment().format("2020 7 1, 14, 58, 21")
              },
              headsign: "Ongar",
              type: "Dublin Bus",
              route: "39a"
            }
          },
          {
            distance: 321,
            duration: 226,
            start: { lat: 53.34212669999999, lng: -6.258003599999999 },
            stop: { lat: 53.3443633, lng: -6.2593112 },
            mode: "WALKING"
          }
        ]
      }
    ];
    
    function Routes() {
      return (
        <div className="App">
          <div className="posts">
            {dueTimes.map((item, itemIndex) => {
              return (
                <Fragment key={itemIndex}>
                  <h4>{item.distance}</h4>
                  <p>{item.start.time}</p>
                  <span>
                    {item.steps.map((step, stepIndex) => (
                      <Fragment key={stepIndex}>
                        <p>{step.distance}</p>
                      </Fragment>
                    ))}
                  </span>
                </Fragment>
              );
            })}
          </div>
        </div>
      );
    }
    
    export default Routes;
    

    Here an example.

    【讨论】:

    • 这太完美了。谢谢!
    猜你喜欢
    • 2020-09-24
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    相关资源
    最近更新 更多