简体   繁体   中英

ReactJS - How to pass JSON data between pages using state?

I have a page that displays a list of building consumed from a REST API; my goal is to display detailed information about the building on another page (detail page) when the building url is clicked. The problem is that when the url is clicked, it loads the details page, but none of the data from the API is showing (content is blank)

On the "list buildings page", I have the URL set up like so :

<NavLink
          className="url-temp"
          to={`/buildingdetails/${building.crgBuildingid}`}
        >Details</NavLink>

**Inside the "details page, I have the componet set up:"

import React, { Component } from "react";
import moment from 'moment';
import { getAuditTypeDescFromId, allAuditTypes, auditTypeToIdMap } from '../constants/audit-types';
import { getCodeTypeDescFromId, allCodeTypes, codeTypeToIdMap } from '../constants/code-types';
import { NavLink } from "react-router-dom";
import { withRouter } from 'react-router'

class Buildingdetails extends Component {
    constructor(props) {
        super(props);
        this.state = {
            buildings: [],
            isLoaded: false,
        }
    }

    componentDidMount() {
        const buildingId = this.props.match.params.id;

        const url = `http://...../buildings/${buildingId}`
        fetch(url)
            .then(res => res.json())
            .then(buildings => {
                isLoaded: true,
                    this.setState({ buildings })
            });
    }

    render() {

        var { isLoaded, buildings } = this.state;
        if (!isLoaded) {
            return <div>Loading...</div>
        }
        else {
            // print properties from this.state.building.crgName
            return (
                <div className="appcontent-inner">
                    <p>Building Details</p>
                   <div>
                       {buildings.map(building => (
                           <div key={building.id}>
                                <b>Building Name:</b> this.state.building.crgName
                           </div>
                       ))};
                   </div>
                </div>
            );

        }
    }
}
export default withRouter(Buildingdetails);

This is a sample of the JSON for the details page:

{
    "$id": "1",
    "Id": null,
    "crgName": “Walmart”,
    "crgManagerspecialistid": {
        "$id": "2",
        "Id": “00000-111-698-2333-123456”,
        “ContactName": "contact",
        "Name": “Jane Doe”,
        "KeyAttributes": [],
        "RowVersion": null
    },
    "crgOpeningdate": "2018-09-03T11:38:23",
    "crgManagerid": {
        "$id": "3",
        "Id": “0000-7312-e411-abcd-0050568571f6",
        "LogicalName": "crg_energyprogram",
        "Name": “Janet kay”,
        "KeyAttributes": [],
        "RowVersion": null
    }
}

could I get some guidance as to what I'm going wrong? Thank you in advance

Try updating your componentDidMount() , specifically the final then() . That block has a combination of different syntax that could be causing issues. isLoaded needs to be put inside the object being passed setState() to ensure it get's updated as well no matter what.

componentDidMount() {
  const buildingId = this.props.match.params.id;
  const url = `http://...../buildings/${buildingId}`;

  fetch(url)
    .then(res => res.json())
    .then(buildings => {      
      this.setState({ isLoaded: true, buildings });
    });
  }

This also assumes your react-router-dom Route is as follows:

<Route path="/buildingdetails/:id" component={Buildingdetails} />

Hopefully that helps!

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