【问题标题】:React Routing Menu - data handling best practiceReact Routing Menu - 数据处理最佳实践
【发布时间】:2020-03-01 13:15:52
【问题描述】:

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

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

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

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 方式,还是在 React 中做这种菜单的某种模式,以便维护更合理?

【问题讨论】:

    标签: javascript reactjs routing react-router react-router-dom


    【解决方案1】:

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

    Route.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 属性。 您可以在 DisplayPaneMenuBar 中导入 Route.js 并遍历它以生成动态路由。

    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 就会为您处理它。

    【讨论】:

    • 这里是这种方法的问题,我不太清楚是否非常有害或只是一点点:这个 Route.js 充其量是 util,在这种方法中,util 正在导入组件,打破层结构
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    相关资源
    最近更新 更多