【问题标题】:How to get nested JSON data in ReactJS如何在 ReactJS 中获取嵌套的 JSON 数据
【发布时间】:2019-02-05 19:31:41
【问题描述】:

我正在使用 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"

我做错了什么。请帮帮我

【问题讨论】:

  • this.state.devicetype的初始值是多少?我的猜测是您的组件在设置 this.state.devicetype.data 以响应 axios 调用之前渲染,因此初始渲染试图访问一个不存在的对象(尚)。
  • @christian 我的 this.state.devicetype 的初始值为 {} 空对象。
  • 如果我的组件在“this.state.devicetype.data”设置为 axios 调用之前渲染。那我该如何解决呢。
  • 这取决于您希望您的 UI 如何处理这种情况。通常这种行为是可取的,因为它使您有机会在加载数据时显示“正在加载...”消息,否则在加载数据之前您的组件不会呈现。您可以在 render() 函数中添加 if 语句来处理尚未加载数据的情况。在伪代码中:if (dataIsNotLoaded) displayLoadingMessage else displayData

标签: javascript json reactjs


【解决方案1】:

您需要在访问嵌套对象之前进行条件检查,例如

   if(devicetype.data){
       console.log(devicetype.data.device_elements);
       console.log(devicetype.data.type_name);
   }

【讨论】:

  • 这个方法有效。你能解释一下为什么在访问嵌套对象之前有必要进行条件检查吗?谢谢
  • 因为 devicetype.data 在初始渲染时未定义或为空,但您直接访问 devicetype.data.type_name 这将不起作用,因为在初始渲染中 devicetype.data 未定义
猜你喜欢
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
相关资源
最近更新 更多