我有一个简单的 React 组件,并尝试在中显示嵌套的 JSON 对象render
.
// React Component
class NodeDetail extends React.Component {
constructor(props) {
super(props);
const node = {};
this.state = {
node
}
}
componentDidMount() {
Node.getNode(this.props.node_id).then((result) => {
console.log(result.data);
this.setState(() => ({node: result.data}));
}).catch(function(error) {
// TODO: handle error
});
}
render() {
return (
<div>
{this.state.node.node_status.name}
</div>
);
}
};
export default NodeDetail;
这是 JSON(存储在result.data
) 从 Rails API 返回(为简洁起见,删除了一些字段):
{
"id":1234,
"name":"some-node",
"created_at":"2018-05-18T15:23:24.012Z",
"hostname":"some-host",
"ip":"10.XXX.XXX.XXX",
"mac":"24:6e:96:XX:11:XX",
"node_status":{
"id":2,
"name":"Parked"
}
}
当我访问 React 中的根级别属性时this.state.node.mac
,它返回24:6e:96:XX:11:XX
.
当我尝试访问name
属性在node_status
using this.state.node.node_status.name
,我收到以下错误:
Uncaught TypeError: Cannot read property 'name' of undefined
我也尝试过this.state.node['node_status'].name
,和同样的错误。
为什么我无法在 JSON 中访问该对象,而它显然就在那里?