如何使用FetchAPI嵌套相同对象的数组 [英] How to use FetchAPI nested Arrays of same object

查看:114
本文介绍了如何使用FetchAPI嵌套相同对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示菜单,该菜单可以具有父子关系,它具有扁平结构,可以正常工作,但嵌套对象无法执行此操作. 以下是JSON和reactJS代码. JSON-

I am trying to show menu where it can have parent child relationship, with flat structure it is working fine but with nested objects not able to do it. The below is the JSON and reactJS code. JSON -

{
  "data": [
    {
      "to": "#a-link",
      "icon": "spinner",
      "label": "User Maintenance"
    },
    {
      "content": [
        {
          "to": "#b1-link",
          "icon": "apple",
          "label": "System Controls"
        },
        {
          "to": "#b2-link",
          "icon": "user",
          "label": "User Maintenance"
        }
      ],
      "icon": "gear",
      "label": "System Preferences"
    },
    {
      "to": "#c-link",
      "icon": "gear",
      "label": "Configuration"
    }
  ]
}

ReactJS代码-

ReactJS code -

export default class MenuComponent extends Component {
  constructor() {
    super();
    this.state = {}
  }

componentDidMount(){
  fetch('http://localhost:8084/Accounting/rest/v1/company/menu?request=abc')
  .then(response => response.json())
  .then(parsedJSON => parsedJSON.data.map(menu => (
    {
      to: `${menu.to}`,
      icon: `${menu.icon}`,
      label: `${menu.label}`
      // content: `${menu.content}`
    }
  )))
  .then(content => this.setState({
    content
  }))
}

  render() {
    console.log('333');
    console.log(this.state.content);
    return (
      <MetisMenu content={this.state.content} activeLinkFromLocation />
    )
  }
}

在JSON中,您可以看到系统偏好设置"具有嵌套内容.

In JSON you can see the 'System Preference' has nested content.

推荐答案

尝试此代码

 class MenuComponent extends Component {
  constructor() {
    super();
    this.state = {
    content : []
    }
  }

componentDidMount(){
  fetch('http://localhost:8084/Accounting/rest/v1/company/menu?request=abc')
  .then(response => response.json())
  .then(parsedJSON => parsedJSON.data.map(menu => (
    {
      to: `${menu.to}`,
      icon: `${menu.icon}`,
      label: `${menu.label}`
      // content: `${menu.content}`
    }
  )))
  .then(content => this.setState({
    content
  }))
}

  render() {
    const {content} = this.state
    if(content === undefined){
      return <div>Content not found</div>;
    }
    if(content.length === 0){
     return <div>Loading</div>;
    }
    return (
            <MetisMenu content={content} activeLinkFromLocation />
    )
  }
}
export default MenuComponent 

这篇关于如何使用FetchAPI嵌套相同对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆