我目前正在努力使用react路由器v4嵌套路由。

中的路由配置是最接近的例子 React-Router v4文档。

我想把我的应用程序分成2个不同的部分。

一个前台和一个管理区域。

我在想这样的事情:

<Match pattern="/" component={Frontpage}>
  <Match pattern="/home" component={HomePage} />
  <Match pattern="/about" component={AboutPage} />
</Match>
<Match pattern="/admin" component={Backend}>
  <Match pattern="/home" component={Dashboard} />
  <Match pattern="/users" component={UserPage} />
</Match>
<Miss component={NotFoundPage} />

前端的布局和风格与管理区域不同。在frontpage中,home, about,还有一个应该是子路由。

/home应该呈现在Frontpage组件中,/admin/home应该呈现在Backend组件中。

我尝试了一些其他的变化,但我总是以不点击/home或/admin/home结束。

最终解决方案:

这是我现在使用的最终解决方案。这个例子还有一个全局错误组件,就像传统的404页面一样。

import React, { Component } from 'react';
import { Switch, Route, Redirect, Link } from 'react-router-dom';

const Home = () => <div><h1>Home</h1></div>;
const User = () => <div><h1>User</h1></div>;
const Error = () => <div><h1>Error</h1></div>

const Frontend = props => {
  console.log('Frontend');
  return (
    <div>
      <h2>Frontend</h2>
      <p><Link to="/">Root</Link></p>
      <p><Link to="/user">User</Link></p>
      <p><Link to="/admin">Backend</Link></p>
      <p><Link to="/the-route-is-swiggity-swoute">Swiggity swooty</Link></p>
      <Switch>
        <Route exact path='/' component={Home}/>
        <Route path='/user' component={User}/>
        <Redirect to={{
          state: { error: true }
        }} />
      </Switch>
      <footer>Bottom</footer>
    </div>
  );
}

const Backend = props => {
  console.log('Backend');
  return (
    <div>
      <h2>Backend</h2>
      <p><Link to="/admin">Root</Link></p>
      <p><Link to="/admin/user">User</Link></p>
      <p><Link to="/">Frontend</Link></p>
      <p><Link to="/admin/the-route-is-swiggity-swoute">Swiggity swooty</Link></p>
      <Switch>
        <Route exact path='/admin' component={Home}/>
        <Route path='/admin/user' component={User}/>
        <Redirect to={{
          state: { error: true }
        }} />
      </Switch>
      <footer>Bottom</footer>
    </div>
  );
}

class GlobalErrorSwitch extends Component {
  previousLocation = this.props.location

  componentWillUpdate(nextProps) {
    const { location } = this.props;

    if (nextProps.history.action !== 'POP'
      && (!location.state || !location.state.error)) {
        this.previousLocation = this.props.location
    };
  }

  render() {
    const { location } = this.props;
    const isError = !!(
      location.state &&
      location.state.error &&
      this.previousLocation !== location // not initial render
    )

    return (
      <div>
        {          
          isError
          ? <Route component={Error} />
          : <Switch location={isError ? this.previousLocation : location}>
              <Route path="/admin" component={Backend} />
              <Route path="/" component={Frontend} />
            </Switch>}
      </div>
    )
  }
}

class App extends Component {
  render() {
    return <Route component={GlobalErrorSwitch} />
  }
}

export default App;

当前回答

React Router v5的完整答案。


const Router = () => {
  return (
    <Switch>
      <Route path={"/"} component={LandingPage} exact />
      <Route path={"/games"} component={Games} />
      <Route path={"/game-details/:id"} component={GameDetails} />
      <Route
        path={"/dashboard"}
        render={({ match: { path } }) => (
          <Dashboard>
            <Switch>
              <Route
                exact
                path={path + "/"}
                component={DashboardDefaultContent}
              />
              <Route path={`${path}/inbox`} component={Inbox} />
              <Route
                path={`${path}/settings-and-privacy`}
                component={SettingsAndPrivacy}
              />
              <Redirect exact from={path + "/*"} to={path} />
            </Switch>
          </Dashboard>
        )}
      />
      <Route path="/not-found" component={NotFound} />
      <Redirect exact from={"*"} to={"/not-found"} />
    </Switch>
  );
};

export default Router;
const Dashboard = ({ children }) => {
  return (
    <Grid
      container
      direction="row"
      justify="flex-start"
      alignItems="flex-start"
    >
      <DashboardSidebarNavigation />
      {children}
    </Grid>
  );
};

export default Dashboard;

Github回购在这里。https://github.com/webmasterdevlin/react-router-5-demo

其他回答

在react-router-v4中,不嵌套<Routes />。相反,将它们放在另一个<Component />中。


例如

<Route path='/topics' component={Topics}>
  <Route path='/topics/:topicId' component={Topic} />
</Route>

应该成为

<Route path='/topics' component={Topics} />

with

const Topics = ({ match }) => (
  <div>
    <h2>Topics</h2>
    <Link to={`${match.url}/exampleTopicId`}>
      Example topic
    </Link>
    <Route path={`${match.path}/:topicId`} component={Topic}/>
  </div>
) 

下面是一个直接来自react-router文档的基本示例。

我成功地使用Switch来定义嵌套路由,并在根路由之前定义嵌套路由。

<BrowserRouter>
  <Switch>
    <Route path="/staffs/:id/edit" component={StaffEdit} />
    <Route path="/staffs/:id" component={StaffShow} />
    <Route path="/staffs" component={StaffIndex} />
  </Switch>
</BrowserRouter>

参考:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Switch.md

React Router v5的完整答案。


const Router = () => {
  return (
    <Switch>
      <Route path={"/"} component={LandingPage} exact />
      <Route path={"/games"} component={Games} />
      <Route path={"/game-details/:id"} component={GameDetails} />
      <Route
        path={"/dashboard"}
        render={({ match: { path } }) => (
          <Dashboard>
            <Switch>
              <Route
                exact
                path={path + "/"}
                component={DashboardDefaultContent}
              />
              <Route path={`${path}/inbox`} component={Inbox} />
              <Route
                path={`${path}/settings-and-privacy`}
                component={SettingsAndPrivacy}
              />
              <Redirect exact from={path + "/*"} to={path} />
            </Switch>
          </Dashboard>
        )}
      />
      <Route path="/not-found" component={NotFound} />
      <Redirect exact from={"*"} to={"/not-found"} />
    </Switch>
  );
};

export default Router;
const Dashboard = ({ children }) => {
  return (
    <Grid
      container
      direction="row"
      justify="flex-start"
      alignItems="flex-start"
    >
      <DashboardSidebarNavigation />
      {children}
    </Grid>
  );
};

export default Dashboard;

Github回购在这里。https://github.com/webmasterdevlin/react-router-5-demo

**这段代码适用于v6**

index.js

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<App />}>
          <Route path="login" element={<Login />} />
          <Route path="home" element={<Home />} />
        </Route>
      </Routes>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

App.js:

function App(props) {
  useEffect(() => {
    console.log('reloaded');
// Checking, if Parent component re-rendering or not *it should not be, in the sense of performance*, this code doesn't re-render parent component while loading children
  });
  return (
    <div className="App">
      <Link to="login">Login</Link>
      <Link to="home">Home</Link>
      <Outlet /> // This line is important, otherwise we will be shown with empty component
    </div>
  );
}

login.js:

const Login = () => {
    return (
        <div>
            Login Component
        </div>
    )
};

home.js:

const Home= () => {
    return (
        <div>
            Home Component
        </div>
    )
};

React路由器v6

允许使用嵌套路由(如v3)和分离的、分离的路由(v4, v5)。

嵌套的路线

对于小/中型应用,将所有路由放在一个地方:

<Routes>
  <Route path="/" element={<Home />} >
    <Route path="user" element={<User />} /> 
    <Route path="dash" element={<Dashboard />} /> 
  </Route>
</Routes>

const App = () => { return ( <BrowserRouter> <Routes> // /js is start path of stack snippet <Route path="/js" element={<Home />} > <Route path="user" element={<User />} /> <Route path="dash" element={<Dashboard />} /> </Route> </Routes> </BrowserRouter> ); } const Home = () => { const location = useLocation() return ( <div> <p>URL path: {location.pathname}</p> <Outlet /> <p> <Link to="user" style={{paddingRight: "10px"}}>user</Link> <Link to="dash">dashboard</Link> </p> </div> ) } const User = () => <div>User profile</div> const Dashboard = () => <div>Dashboard</div> ReactDOM.render(<App />, document.getElementById("root")); <div id="root"></div> <script src="https://unpkg.com/react@16.13.1/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@16.13.1/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/history@5.0.0/umd/history.production.min.js"></script> <script src="https://unpkg.com/react-router@6.0.0-alpha.5/umd/react-router.production.min.js"></script> <script src="https://unpkg.com/react-router-dom@6.0.0-alpha.5/umd/react-router-dom.production.min.js"></script> <script>var { BrowserRouter, Routes, Route, Link, Outlet, useNavigate, useLocation } = window.ReactRouterDOM;</script>

替代方案:通过useRoutes将路由定义为纯JavaScript对象。

单独的通道

你可以使用分离路由来满足大型应用程序的需求,比如代码拆分:

// inside App.jsx:
<Routes>
  <Route path="/*" element={<Home />} />
</Routes>

// inside Home.jsx:
<Routes>
  <Route path="user" element={<User />} />
  <Route path="dash" element={<Dashboard />} />
</Routes>

const App = () => { return ( <BrowserRouter> <Routes> // /js is start path of stack snippet <Route path="/js/*" element={<Home />} /> </Routes> </BrowserRouter> ); } const Home = () => { const location = useLocation() return ( <div> <p>URL path: {location.pathname}</p> <Routes> <Route path="user" element={<User />} /> <Route path="dash" element={<Dashboard />} /> </Routes> <p> <Link to="user" style={{paddingRight: "5px"}}>user</Link> <Link to="dash">dashboard</Link> </p> </div> ) } const User = () => <div>User profile</div> const Dashboard = () => <div>Dashboard</div> ReactDOM.render(<App />, document.getElementById("root")); <div id="root"></div> <script src="https://unpkg.com/react@16.13.1/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@16.13.1/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/history@5.0.0/umd/history.production.min.js"></script> <script src="https://unpkg.com/react-router@6.0.0-alpha.5/umd/react-router.production.min.js"></script> <script src="https://unpkg.com/react-router-dom@6.0.0-alpha.5/umd/react-router-dom.production.min.js"></script> <script>var { BrowserRouter, Routes, Route, Link, Outlet, useNavigate, useLocation } = window.ReactRouterDOM;</script>