【问题标题】:How to make dynamic Sidebar from Json api?如何从 Json api 制作动态侧边栏?
【发布时间】:2020-08-19 23:09:55
【问题描述】:

我正在尝试从 Json API 创建一个 React 动态侧边栏。

我需要使用以下三个条件在 React 中进行双重迭代的编码辅助:

  1. 如果 json 元素 id === 0 ===> 外部 1 级菜单项

  2. if json element[i] id ===[j] parent_id ===> 2 级子菜单项

  3. if parent_id[i]===[j] id && [j]parent_id===0 ===>3 级子菜单项

但是我可以实现外层MenuItem。但我无法创建 SubMenuItem。

请帮我解决这个问题。请看附图。谢谢

 class App extends Component {

    constructor(props) {
    super(props);
    this.state = {
        mz:[
      {
          "id": 1,
          "name": "Menu1",
          "parent_id": 0
      },
      {
          "id": 9,
          "name": "SubMenu1-Menu1",
          "parent_id": 1
      },
      {
        "id": 26,
        "name": "8989",
        "parent_id": 9
      },
      {
          "id": 10,
          "name": "SubMenu2-Menu1",
          "parent_id": 1
      },
      {
          "id": 2,
          "name": "Menu2",
          "parent_id": 0
      },
      {
          "id": 11,
          "name": "SubMenu1-Menu2",
          "url": "",
          "order": 210,
          "type": 3,
          "is_active": true,
          "parent_id": 2
      },
      {
          "id": 12,
          "name": "SubMenu2-Menu2",
          "url": "",
          "order": 220,
          "type": 3,
          "is_active": true,
          "parent_id": 2
      }],};
    }

 render() {
    return (
      <div>
       {this.state.api.filter((el) => (el.parent_id === 0 ? el.name : null)).map((el) => (
          <ReactBootStrap.Navbar  >          
             {el.name}
                <ReactBootStrap.NavDropdown>
                  {(el.parent_id === el.id ? el.name : null).map((el) =>el.name)}//I CANNOT ITERATE CORRECTLY THIS PART
                </ReactBootStrap.NavDropdown>
          </ReactBootStrap.Navbar>
        ))}
      </div>
    );
  }
}
export default App;

【问题讨论】:

    标签: json reactjs dynamic react-sidebar


    【解决方案1】:

    看这张地图:

    this.state.mz.map(item => {
        if(item.parent_id === 0){
            output[item.id] = item
        } else {
            if(!output[item.parent_id]['submenu']){
                output[item.parent_id]['submenu'] = {}
            }
            output[item.parent_id]['submenu'][item.id] = item
        }
    })
    

    【讨论】:

    • “输出”循环类型“let output = []”之前的一个简单变量
    猜你喜欢
    • 2021-09-07
    • 2022-01-26
    • 2015-10-20
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 2021-12-15
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多