react-router-dom:如何在Switch中拥有多个具有各自路径的“外壳”?

我遇到的情况是我的应用程序中的页面有两个主要的“外壳”。第一个外壳用于“ unauth”页面登录流程(背景图像,用户界面文件),第二个外壳用于主仪表板(导航栏,侧边栏等)。

以下代码是我尝试简化遇到的问题的尝试。有人可以告诉我如何通过react-router-dom正确实现吗?

  <BrowserRouter>
    <Switch>
      <Route component={Shell1}>
        <Route path="/test1" exact component={() => <div>Test 1</div>} />
        <Route path="/test2" exact component={() => <div>Test 2</div>} />
      </Route>
      <Route component={Shell2}>
        <Route path="/test3" exact component={() => <div>Test 3</div>} />
        <Route path="/test4" exact component={() => <div>Test 4</div>} />
      </Route>
    </Switch>
  </BrowserRouter>

我从another StackOverflow post处获得了这种尝试,但是上面的代码无效。导航到/ test1时,Shell1(只是一个表示Shell1的div)不会显示,并且/ test3 + / test4根本不起作用。

这是一个沙盒代码,演示:https://codesandbox.io/s/react-example-362ow

谢谢。

tong817480 回答:react-router-dom:如何在Switch中拥有多个具有各自路径的“外壳”?

基本上,您将需要嵌套so之类的路由,其中​​父组件Route包裹子Route

以下是一些需要身份验证的示例:https://codesandbox.io/s/yqo75n896x(使用Redux状态)或https://codesandbox.io/s/5m2690nn6n(使用React状态)

工作示例:

Edit Nested Routes Example


index.js

import ReactDOM from "react-dom";
import React,{ Fragment } from "react";
import { BrowserRouter,Route,Switch,Link } from "react-router-dom";
import Shell1 from "./shell1";
import Shell2 from "./shell2";

function NavBar() {
  return (
    <Fragment>
      <Link to="/shell1/test1">Test1</Link>
      <br />
      <Link to="/shell1/test2">Test2</Link>
      <br />
      <Link to="/shell2/test3">Test3</Link>
      <br />
      <Link to="/shell2/test4">Test4</Link>
    </Fragment>
  );
}

function App() {
  return (
    <BrowserRouter>
      <div>
        <NavBar />
        <Route path="/shell1" component={Shell1} />
        <Route path="/shell2" component={Shell2} />
      </div>
    </BrowserRouter>
  );
}

ReactDOM.render(<App />,document.getElementById("root"));

shell1.js

import React from "react";
import { Route,Switch } from "react-router-dom";

export default function Shell1({ match }) {
  return (
    <div>
      <div>Shell 1</div>
      <Switch>
        <Route
          exact
          path={`${match.url}/test1`}
          component={() => <div>Test 1</div>}
        />
        <Route
          exact
          path={`${match.url}/test2`}
          component={() => <div>Test 2</div>}
        />
      </Switch>
    </div>
  );
}

shell2.js

import React from "react";
import { Route,Switch } from "react-router-dom";

export default function Shell2({ match }) {
  return (
    <div>
      <div>Shell 2</div>
      <Switch>
        <Route
          exact
          path={`${match.url}/test3`}
          component={() => <div>Test 3</div>}
        />
        <Route
          exact
          path={`${match.url}/test4`}
          component={() => <div>Test 4</div>}
        />
      </Switch>
    </div>
  );
}
本文链接:https://www.f2er.com/3169565.html

大家都在问