我试图使用React从API解析JSON对象,但我无法弄清楚如何获取子对象的值。从JSON的根获取值工作正常。我错过了什么?
JSON:
{
"AllocDirStats": {
"Available": 511630798848,
"Device": "",
"InodesUsedPercent": 0,
"Mountpoint": "",
"Size": 536868810752,
"Used": 25238011904,
"UsedPercent": 4.700964443929746
},
"CPU": [
{
"CPU": "",
"Idle": 100,
"System": 0,
"Total": 0,
"User": 0
}
],
"CPUTicksConsumed": 0,
"DiskStats": [
{
"Available": 511630798848,
"Device": "C:",
"InodesUsedPercent": 0,
"Mountpoint": "C:",
"Size": 536868810752,
"Used": 25238011904,
"UsedPercent": 4.700964443929746
}
],
"Memory": {
"Available": 30044225536,
"Free": 0,
"Total": 34359328768,
"Used": 4315103232
},
"Timestamp": 1494912754632734000,
"Uptime": 1747472
}
JSX:
var App = React.createClass({
getInitialState: function() {
return {
client: []
}
},
componentDidMount: function() {
const makeRequest = () => axios.get("http://@Model.IP:4646/v1/client/stats").then(({ data }) => this.setState({ client: data }));
this.serverRequest = makeRequest();
this.poll = setInterval(() => {
this.serverRequest = makeRequest();
}, 60000) // Poll every 60 seconds
},
componentWillUnmount: function() {
this.serverRequest.abort();
clearInterval(this.poll)
},
render: function() {
const { client } = this.state;
return (
<div>
{client.Memory.Available}
</div>
)
}
});
ReactDOM.render(<App />, document.getElementById("root"));
Uncaught TypeError: Cannot read property 'Available' of undefined
但是,如果我将{clinet.Memory.Available}
更改为{client.Uptime}
,那么它可以正常工作,我会得到1747472
。
答案 0 :(得分:4)
似乎您的render
函数甚至在您的API调用成功之前运行代码。因此,代码将尝试访问空client
状态,默认情况下为[]
。该计划找不到Available
,因为Memory
是undefined
的{{1}}。
我的建议是先在渲染功能中检查状态。因为JS是类型杂耍,你可以改变它:
[]