【问题标题】:How to use FetchAPI nested Arrays of same object如何使用相同对象的 FetchAPI 嵌套数组
【发布时间】:2018-08-10 04:18:50
【问题描述】:

我正在尝试显示可以具有父子关系的菜单,平面结构可以正常工作,但嵌套对象无法做到这一点。 下面是 JSON 和 reactJS 代码。 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 代码 -

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 中,您可以看到“系统偏好设置”具有嵌套内容。

【问题讨论】:

  • 您是否尝试过在构造函数中将内容初始化为状态?
  • 你可以在 menu.content.map(menuContentItem => ... etc 上做另一个 .map
  • @SumanKundu - 我是 reactjs 的新手,请帮帮我。
  • @GavinThomas - 我们可以做到,但如果重复出现在多个级别,例如 4-5 会怎样

标签: reactjs metismenu


【解决方案1】:

试试这个代码

 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 

【讨论】:

  • index 和 cont 是未定义的变量。请让我知道我们需要在哪里定义它们以及如何定义它们
  • 同样的问题只有平面结构出现了,在系统偏好中它没有显示子菜单项
  • 我正在使用 react-metismenu 组件 (npmjs.com/package/react-metismenu),不知道在哪里更改第二部分
  • 好的,那么它必须在没有第二部分的情况下工作。现在究竟显示什么
  • 子菜单项未显示在系统偏好设置中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 2019-08-15
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
相关资源
最近更新 更多