我是一个.NET开发人员,正在构建我的第一个ReactJS / AgGrid应用程序,并且我有一个WEB API,它根据以下内容返回JSON:
public class CarbonCostsView
{
public DateTime TradeDate { get; set; }
public Int16 HourEnding { get; set; }
public List<CarbonCosts> CarbonCosts { get; set; }
}
我试图将返回的JSON解析为三个对象,但不知道如何。最终,前两个元素(TradeDate和HourEnding)将串联到标题消息中。
JSON如下:
{
"tradeDate":"2019-04-02T00:00:00",
"hourEnding":5,
"carbonCosts":[
{
"id":101,
"displayName":"Delta 1X0",
"tradeDate":"2019-04-02T00:00:00",
"hourEnding":5,
"manMin":10.410000,
"base":7.380000,
"db":null,
"pag":null
},
{
"id":102,
"displayName":"Delta 1X1",
"tradeDate":"2019-04-02T00:00:00",
"hourEnding":5,
"manMin":7.120000,
"base":5.230000,
"db":null,
"pag":null
}
]
}
这是代表ReactJS / AgGrid的JS。
const columnDefs = [
{ headerName: "Plant", field: "plantName", width: 120, rowGroup: true, sortable: true, filter: true },
{ headerName: "Man Min", field: "manMin", width: 80 },
{ headerName: "Base", field: "base", width: 100 },
{ headerName: "+DB", field: "db", width: 100 },
{ headerName: "+PAG", field: "pag", width: 100 },
{ headerName: "+RA", field: "ra", width: 100 },
];
class App extends Component {
constructor() {
super();
this.state = {
columnDefs: columnDefs,
header: {}
}
}
componentDidMount() {
fetch('http://localhost:53884/api/OperationalCosts')
.then(result => result.json())
.then(rowData => this.setState({ rowData }))
}
render() {
console.log(this.state.rowData);
return (
<div
className="ag-theme-balham"
style={{
height: '700px',
width: '1000px'
}}
>
<h1> Carbon Costs</h1>
<AgGridReact
columnDefs={this.state.columnDefs}
rowData={this.state.rowData}>
</AgGridReact>
</div>
);
}
}
我怀疑我要找的“魔术”发生在这里吗?在本节的某个地方,我可以将JSON分解为三个离散的对象?
.then(result => result.json())
.then(rowData => this.setState({ rowData }))
答案 0 :(得分:0)
好吧,答案似乎是:
class App extends Component {
constructor() {
super();
this.state = {
columnDefs: columnDefs,
header: {}
}
}
componentDidMount() {
fetch('http://localhost:53884/api/OperationalCosts')
.then(result => result.json())
.then(foobar => this.setState(
{ TradeDate: foobar.TradeDate,
HourEnding: foobar.HourEnding,
CarbonCosts: foobar.carbonCosts }))
}
render() {
return (
<div
className="ag-theme-balham"
style={{
height: '700px',
width: '1000px'
}}
>
<h1> Carbon Costs</h1>
<AgGridReact
columnDefs={this.state.columnDefs}
rowData={this.state.CarbonCosts}>
</AgGridReact>
</div>
);
}
}
感谢您将我推向正确的方向。
(仍然感觉很尴尬:ReactJS-和js整体-对我来说是陌生的)