首页 > 解决方案 > React Routing Menu - 数据处理最佳实践

问题描述

我正在尝试为我的 React 应用程序创建一个菜单,如下所示:

在此处输入图像描述

列表本身很简单。但现在我有包含 2 个子组件的主要组件:

class App extends Component {
  render() {
    return (
      <MenuBar/>
      <DisplayPane/>
    )
  }
}

Component 包含所有的MenuBar菜单构建逻辑,其中有一堆Link组件。该DisplayPane组件有几个Route组件:

class DisplayPane extends Component {
  render() {
    return (
      <Route path="/a" component={A} />
      <Route path="/b" component={B} />
      <Route path="/c" component={C} />
    )
  }
}

但现在我有一个问题,每当我想添加/删除/修改组件/路由时,我需要更新 2 个地方,这对我来说没有意义。

这是处理这种情况的反应方式,还是在 React 中做这种菜单的某种模式,所以维护更合理?

标签: javascriptreactjsroutingreact-routerreact-router-dom

解决方案


对我来说似乎很好。但是,如果您想要一个更通用的方法,您可以创建一个单独的文件来存储实际的组件绑定及其路由并迭代以动态生成路由及其链接。你可以这样做:

路由.js

export default [
    {
        path : "/a",
        component : A,
        target : "",
        isExact : true // You can add more objects to configure your route/link
    },
    {
        path : "/b",
        component : B,
        target : "",
        isExact : true
    },
    {
        path : "/c",
        component : C,
        target : "",
        isExact : true
    },
]

您可以导入组件Route.js并将它们映射到component属性。Route.js您可以在您的内部导入DisplayPaneMenuBar遍历它以生成动态路由。

DisplayPane.js

class DisplayPane extends Component {
    render() {
      return routesObj.map((route,index)=> {
          return <Route key={index} exact={route.isExact} path={route.path} component={route.component}/>
        })
    }
  }

同样,您也可以在其中导入相同的对象MenuBar并使用map它来渲染Link. 这样,您只需要在数组中创建另一个对象,map 就会为您处理它。


推荐阅读