更改组件内的路线会更改整个页面

时间:2019-07-16 08:11:56

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

我有一个应用程序,当用户登录时,他/她被带到仪表板,那里有一个侧边栏,其中有到各个组件(如(家庭,搜索,myaccount)的链接),并且我在其中包含了BrowserRouter该组件以及已定义的路线和相应组件,但是当我单击其中一个链接时,整个页面都消失了,并且没有显示任何内容,但是,当第一次加载该页面时,如果我单击其中的任何一个,则会正确地加载home组件。链接无法正常工作

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);

1 个答案:

答案 0 :(得分:0)

您的代码中有多个问题。

Route中,您写了to

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

to中没有Route,您应该使用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中,删除<BrowserRouter>,仅保留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">