简体   繁体   English

React Router 4为所有路由呈现相同的组件

[英]React router 4 render same component for all routes

So this question is more about the approach I should take to solve this problem. 因此,这个问题更多地是关于我应该解决该问题的方法。

I have a JSON like this 我有这样的JSON

const app = [
  {
    tab: 'Home',
    // content: '<div>This is home</div>',
    nav: [
      {
        tab: 'Dashboard',
        content: '<div>This is Dashboard</div>'
      },
      {
        tab: 'Profile',
        content: '<div>This is Profile</div>'
      },
    ]
  },
  {
    tab: 'About',
    content: '<div>This is About</div>'
  },
  {
    tab: 'Pricing',
    content: '<div>This is Pricing</div>'
  },
];

Now what I would want is setup the entire routes and pages to render the above JSON. 现在,我想要设置整个路由和页面以呈现上述JSON。

Below is the pseudo code: 下面是伪代码:

Approach 1... 方法1 ...

Loop through and for each nav/subnav add Route. 遍历并为每个导航/子导航添加路由。

import {
  BrowserRouter,
  Route,
  NavLink,
} from 'react-router-dom';


const Page = (content) => {
  return (
    <div>{content}</div>
  )
}

<BrowserRouter>
  app.map((nav, i) =>
    <NavLink key={nav.tab} to={`/${nav.tab}`} activeClassName="active">
      {nav.tab}
    </NavLink>
    <Route
      path={`/${nav.tab}`} render={(props) => (
        <Page {...props} pageData={nav.content}>
          if(nav.subNav) {
            nav.subNav.map((subnav, i) =>
              <NavLink key={subnav.tab} to={`/${nav.tab}/${subnav.tab}`} activeClassName="active">
                {nav.tab}
              </NavLink>
              <Route
                path={`/${nav.tab}/${subnav.tab}`} render={(props) => (
                  <Page {...props} pageData={subnav.content} />
                )}
              />
            )          
          }
        </Page>
      )}
    />
  )
</BrowserRouter>

Approach 2 方法2

Would something like this work/be better? 这样的工作会更好吗? Just have 2 routes returning same component, pass the app object to Page and then based on URL render the corresponding data 仅有2条返回相同组件的路由,将app对象传递给Page,然后基于URL渲染相应的数据

const Page = (app) => {
  return (
    // Loop over app
    if(mainNav from URL == tab) {
      if(subNav from URL == tab) {
        <div>{content}</div>
      }
    }

  )
}

<BrowserRouter>
  <Route
    path={'/:mainNav'} render={(props) => (
      <Page {...props} pageData={app} />
    )}
  />
  <Route
    path={'/:mainNav/:subNav'} render={(props) => (
      <Page {...props} pageData={app} />
    )}
  />
</BrowserRouter>

Thanks for reading through and appreciate your help. 感谢您阅读并感谢您的帮助。 If theres another better approach I would love to know! 如果有其他更好的方法,我很想知道!

Try utilizing the exact prop offered in your <Route /> components. 尝试利用<Route />组件中提供的确切道具

<Route exact path="/foo" component={Foo} />

If you have the routes: 如果您有路线:

  • /foo
  • /foo/bar
  • /foo/bar/baz

/foo matches in all three cases. /foo在所有三种情况下都匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM