[英]How to get nested JSON data in ReactJS
I am using axios to fetch data from api.我正在使用 axios 从 api 获取数据。 My router is:
我的路由器是:
<Route exact path='/device/:id/update' render={(props) => <DeviceTypeUpdate {...props} />} />
My componentDidMount is :我的 componentDidMount 是:
componentDidMount() {
console.log('------this.props.match.id----', this.props.match.params.id)
const ied = this.props.match.params.id
axios({
url: 'http://127.0.0.1:8000/api/devicetypeget/'+ied,
method: 'get',
headers: {
'Content-Type' : 'application/json'
}
})
.then(function(response) {
return response;
})
.then(function (devicetype) {
this.setState(function () {
return {devicetype: devicetype, isLoaded: true}
})
}.bind(this))
.catch(function (error) {
this.setState(function () {
return {error, isLoaded: true}
})
}.bind(this))
}
In my render method, I tried to log data in console, as given below:在我的渲染方法中,我尝试在控制台中记录数据,如下所示:
const {error, isLoaded, devicetype} = this.state
console.log('----error----', error);
console.log('----devicetype in render----', devicetype.data);
devicetype.data prints out the JSON object which has nested data in it as given below: devicetype.data 打印出包含嵌套数据的 JSON 对象,如下所示:
assignment_date: {$date: 1548744545634}
device_elements: {type: "switch", name: "board", state: "some state"}
dev_stage: "PLANNING"
type_description: "some description"
type_name: "Board"
_id: 1
when I console.log(devicetype.data.device_elements) or any other attribute It throws an error "TypeError: Cannot read property 'type_name' of undefined"
当我 console.log(devicetype.data.device_elements) 或任何其他属性时它会抛出错误
"TypeError: Cannot read property 'type_name' of undefined"
What am I doing wrong.我究竟做错了什么。 Please help me
请帮我
You need to do conditional check before accessing nested objects like在访问嵌套对象之前,您需要进行条件检查,例如
if(devicetype.data){
console.log(devicetype.data.device_elements);
console.log(devicetype.data.type_name);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.