【问题标题】:Changing routes within a components changes the whole page更改组件内的路由会更改整个页面
【发布时间】:2019-11-24 22:16:30
【问题描述】:

我有一个应用程序,当用户登录时,他/她会被带到仪表板,我有一个侧边栏,其中有各种组件的链接,例如(主页、搜索、我的帐户),并且我在里面包含了 BrowserRouter该组件并定义了路由和相应的组件,但是当我单击其中一个链接时,整个页面都消失了,并且没有显示任何内容,但是当第一次加载页面时,如果我单击任何链接没有正常工作

import React, { Component } from "react";
import { Layout, Menu, Icon, Modal } from "antd";
import jwtDecode from "jwt-decode";
import {
  withRouter,
  Link,
  Switch,
  BrowserRouter,
  Route
} from "react-router-dom";
import Home from "./components/Home";
import Search from "./components/Search";
import MyAccount from "./components/MyAccount";

const { Header, Sider, Content } = Layout;

class Dashboard extends Component {
  state = {
    collapsed: false,
    modalVisible: false
  };

  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed,
      current: 1
    });
  };

  toggleModal = () => {
    this.setState({
      modalVisible: true
    });
  };

  handleOk = () => {
    localStorage.removeItem("user");
    this.setState(
      {
        modalVisible: false
      },
      () => {
        this.props.history.push("/");
      }
    );
  };

  handleCancel = () => {
    this.setState(
      {
        modalVisible: false,
        current: 1
      },
      () => {
        console.log(this.state);
      }
    );
  };

  componentDidMount() {
    const token = localStorage.getItem("user");

    if (token) {
      const decoded = jwtDecode(token);

      if (Date.now() < decoded.exp) {
        console.log("logged out");
        this.props.history.push("/");
      } else {
        console.log("logged in");
        this.props.history.push("/dashboard");
      }
    } else {
      this.props.history.push("/");
    }
  }

  handleClick = e => {
    this.setState({
      current: e.key
    });
  };

  render() {
    return (
      <Layout>
        <Sider
          trigger={null}
          collapsible
          collapsed={this.state.collapsed}
          style={{ minHeight: "100vh" }}
        >
          <Menu
            theme="dark"
            mode="inline"
            defaultSelectedKeys={["1"]}
            style={{ marginTop: "5rem" }}
          >
            <Menu.Item key="1">
              <Link to="dashboard/home" exact="true">
                <Icon type="home" />
                <span>Home</span>
              </Link>
            </Menu.Item>
            <Menu.Item key="2">
              <Link to="dashboard/search" exact="true">
                <Icon type="search" />
                <span>Search</span>
              </Link>
            </Menu.Item>
            <Menu.Item key="3">
              <Link to="dashboard/my-account" exact="true">
                <Icon type="user" />
                <span>My account</span>
              </Link>
            </Menu.Item>
            <Menu.Item key="4" onClick={this.toggleModal}>
              <Icon type="logout" />
              <span>Log out</span>
            </Menu.Item>
          </Menu>
        </Sider>
        <Layout>
          <Header style={{ background: "#fff", paddingLeft: "20px" }}>
            <Icon
              className="trigger"
              type={this.state.collapsed ? "menu-unfold" : "menu-fold"}
              onClick={this.toggle}
            />
          </Header>
          <Content
            style={{
              padding: 24,
              background: "#fff",
              minHeight: 280
            }}
          >
            <Modal
              title="Log out"
              visible={this.state.modalVisible}
              onOk={this.handleOk}
              onCancel={this.handleCancel}
            >
              <p>Are you sure you want to log out?</p>
            </Modal>
            <BrowserRouter>
              <Switch>
                <Route to="/home" component={Home} exact />
                <Route to="/search" component={Search} exact />
                <Route to="/my-account" component={MyAccount} exact />
              </Switch>
            </BrowserRouter>
          </Content>
        </Layout>
      </Layout>
    );
  }
}

export default withRouter(Dashboard);

【问题讨论】:

标签: node.js reactjs react-router-dom


【解决方案1】:

您的代码中存在多个问题。

Route 你写了to

<Route to="/home" component={Home} exact />

Route 中没有to,你应该使用path

<Route path="/home" component={Home} exact />

另一个问题是,

<Link to="dashboard/my-account" exact="true">

你应该以/开始你的路径,不要在这里写exact

<Link to="/dashboard/my-account">

上面的Link 再次不起作用,因为您没有Route 来处理这个问题。

要完成这项工作,您应该像这样使用Link

<Link to="/home">
<Link to="/search">
<Link to="/my-account">

另一个问题是,

this.props.history.push("/");

这也不起作用,因为路径 Route 没有 /

要完成这项工作,您应该拥有Route 的赞,

<Route path="/" component={Home} exact />

请参阅 thisthis 了解有关路由的更多信息。


更新

App.js 中将您的路线更改为此,

<BrowserRouter basename="dashboard"> //for basename refer second link above
    <Switch>
       <Route path="/" component={Dashboard} />
    </Switch>
</BrowserRouter>

Dashboard.js,去掉&lt;BrowserRouter&gt;,只有switch点赞,

<Switch>
  <Route path="/home" component={Home} exact />
  <Route path="/search" component={Search} exact />
  <Route path="/my-account" component={MyAccount} exact />
</Switch>

你的链接应该是,

<Link to="/home">
<Link to="/search">
<Link to="/my-account">

【讨论】:

  • 我按照您的建议进行了所有更改,但它似乎仍然不起作用 ps:- this.props.history.push("/"); 用于我在另一个文件中定义其路线的登录页面
  • 您能否为此创建一个代码框,以便我看看您做了哪些更改。
  • codesandbox.io/embed/upbeat-sky-seefo 在 url 中输入仪表板以查看组件
猜你喜欢
  • 2017-08-19
  • 2021-04-01
  • 2017-02-16
  • 2021-01-13
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
  • 2020-04-07
  • 1970-01-01
相关资源
最近更新 更多