如何获得在ReactJS嵌套JSON数据

问题描述 投票:2回答:1

我使用Axios公司来从API数据。我的路由器是:

<Route exact path='/device/:id/update' render={(props) => <DeviceTypeUpdate {...props} />} />

我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))
}

在我的渲染方法,我试着在控制台上,记录数据下面给出:

const {error, isLoaded, devicetype} = this.state
console.log('----error----', error);
console.log('----devicetype in render----', devicetype.data);

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

当我CONSOLE.LOG(devicetype.data.device_elements)或任何其它属性,则抛出错误"TypeError: Cannot read property 'type_name' of undefined"

我究竟做错了什么。请帮我

javascript json reactjs
1个回答
2
投票

您需要访问像嵌套对象之前做条件检查

   if(devicetype.data){
       console.log(devicetype.data.device_elements);
       console.log(devicetype.data.type_name);
   }
© www.soinside.com 2019 - 2024. All rights reserved.