如何在 React 中的路由器内部正确使用路由器

时间:2021-04-11 07:49:10

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

我正在努力使用“react-router-dom”创建路由。 正在显示默认的“Page1”: as you can see here, 但是我在切换到“Page2”或“Page3”时得到了一个空白页。

如果有人能够查看我的代码,我会很高兴。谢谢!

App.js:

import Layout from "./Layout";
import Login from "./Login";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path={"/"} component={Layout} />
        <Route path={"/login"} component={Login} />
      </Switch>
    </Router>
  );
}

export default App;   

登录.js:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles(() => ({
  root: {
    flexGrow: "1",
    height: "100%",
  },
}));

const Login = () => {
  const classes = useStyles();
  return <div className={classes.root}>Login</div>;
};

export default Login;

Layout.js:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Grid from "@material-ui/core/Grid";
import Header from "./Header";
import Menu from "./Menu";
import Page1 from "./Page1";
import Page2 from "./Page2";
import Page3 from "./Page3";
import { Switch, Route } from "react-router-dom";

const useStyles = makeStyles(() => ({
  root: {
    display: "flex",
    overflow: "hidden",
    backgroundColor: "red",
  },
}));

export default function Layout() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Menu />
      <Grid container direction="column">
        <Grid item xs>
          <Header />
        </Grid>
        <Grid item xs>
          <Switch>
            <Route exact path="/" component={Page1} />
            <Route path="/page2" component={Page2} />
            <Route path="/page3" component={Page3} />
          </Switch>
        </Grid>
      </Grid>
    </div>
  );
}

Menu.js

import { useHistory } from "react-router-dom";
import React, { useState } from "react";
import { makeStyles, withStyles } from "@material-ui/core/styles";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";

const useStyles = makeStyles((theme) => ({
  root: {
    height: "100vh",
    width: "90px",
    backgroundColor: theme.palette.background.menu,
    textAlign: "center",
    justifyContent: "center",
    backgroundColor: "lightblue",
  },
}));

const StyledListItem = withStyles((theme) => ({
  root: {
    flexDirection: "column",
    textAlign: "center",
    opacity: 0.8,
  },
}))(ListItem);

const MainNavMenu = (props) => {
  const [selectedIndex, setSelectedIndex] = useState(0);
  const classes = useStyles(props);
  let history = useHistory();

  // Navigate between pages
  const navigate = (text, index) => {
    setSelectedIndex(index);
    if ("page1" === text) {
      history.push("/");
    } else if ("page2" === text) {
      history.push("/page2");
    } else {
      history.push("/page3");
    }
  };

  return (
    <div className={classes.root}>
      <List>
        {["page1", "page2", "page3"].map((text, index) => (
          <StyledListItem
            button
            key={index}
            selected={selectedIndex === index}
            onClick={() => {
              navigate(text, index);
            }}
          >
            <ListItemText primary={text} />
          </StyledListItem>
        ))}
      </List>
    </div>
  );
};

export default MainNavMenu;

Page1.js(所有页面看起来都一样):

function Page1() {
  return (
    <div>
      <h1>Page 1</h1>
    </div>
  );
}

export default Page1;

4 个答案:

答案 0 :(得分:1)

您的代码中没有 page1 或 page2 路由。这就是为什么你会得到一个空白页面。

答案 1 :(得分:1)

您的应用需要知道它应该通过 /page2 组件处理 /page1Layout。现在不是因为您的 Route 只匹配 exact path={"/"}

您可以删除 exact 以通过 Layout 发送所有流量。由于使用了第一个匹配项,您总是希望从最具体到最不具体列出您的 Route 组件。如果没有 exactRouteLayout 现在属于列表底部。

function App() {
  return (
    <Router>
      <Switch>
        <Route path={"/login"} component={Login} />
        <Route path={"/"} component={Layout} />
      </Switch>
    </Router>
  );
}

您的 Layout 中的路径与 Menu 中的路径不匹配。您在 /page3 中没有 Layout

布局:

<Route exact path="/" component={Page1} />
<Route path="/page1" component={Page2} />
<Route path="/page2" component={Page3} />

菜单:

{["page1", "page2", "page3"].map((text, index) => (

可能您想像这样更改 Layout

<Route exact path="/" component={Page1} />
<Route path="/page2" component={Page2} />
<Route path="/page3" component={Page3} />

我个人会使用 react-router-dom Link 组件进行导航,但您需要以不同的方式处理样式。

答案 2 :(得分:0)

移除应用组件中的精确。因为你放置了精确,所以它不会切换到嵌套组件。

<Switch>
      <Route path={"/"} component={Layout} />
      <Route path={"/login"} component={Login} />
</Switch>

编辑评论

只需命名路由而不是空白,例如“/home”并将空白路由重定向到家。 像这样

<Switch>
      <Route exact path="/" > <Redirect to="/home" /> </Route>
      <Route path={"/home"} component={Layout} />
      <Route path={"/login"} component={Login} />
</Switch>

大多数情况下 page1,page2,page3 都可以工作。如果没有,则实现“useRoutematch”并将路径放在 Layout.js 的 <Route>

答案 3 :(得分:0)

 import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
 import React, { Fragment, useEffect } from 'react';
  <Router>
    <Fragment>
      <Navbar />
      <Switch>
        <Route exact path="/" component={Landing} />
        <Route component={Routes} />
      </Switch>
    </Fragment>
  </Router>