[英]ReactJS - How to pass JSON data between pages using state?
我有一个页面,显示从REST API消耗的建筑物的列表; 我的目标是在点击建筑物网址时在另一页(详细信息页面)上显示有关建筑物的详细信息。 问题是单击该URL时,它将加载详细信息页面,但API中的任何数据均未显示(内容为空白)
在“列出建筑物页面”上,我的网址设置如下 :
<NavLink
className="url-temp"
to={`/buildingdetails/${building.crgBuildingid}`}
>Details</NavLink>
**在“详细信息页面中,我设置了组件”:
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);
这是JSON的详细信息页面的一个示例:
{
"$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
}
}
我可以得到有关我要怎么做的一些指导吗? 先感谢您
尝试更新您的componentDidMount()
,尤其是最后的then()
。 该块具有可能导致问题的不同语法的组合。 需要将isLoaded
放在要传递的setState()
对象内部,以确保无论如何都可以对其进行更新。
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 });
});
}
这也假设您的react-router-dom Route
如下:
<Route path="/buildingdetails/:id" component={Buildingdetails} />
希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.