How to use FetchAPI nested Arrays of same object

白昼怎懂夜的黑 提交于 2019-12-11 17:05:10

问题


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

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


回答1:


Try this code

 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 


来源:https://stackoverflow.com/questions/51778908/how-to-use-fetchapi-nested-arrays-of-same-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!