【问题标题】:How to use react router反应路由器的使用方法
【发布时间】:2019-03-19 02:40:20
【问题描述】:

我正在构建一个具有不同页面的应用程序,我想知道如何重组我的路由我想在“/”上加载登录组件,并且我有 this.props.history.push("/homepage" )在登录页面上,成功登录后打开主页我在主页中有一个导航栏,其中包含不同的链接,当单击链接时,我是否会解决在主页中加载组件的问题,并且我希望导航栏仅保留在主页中并加载组件下一步对它。我是新来的反应。这种情况的最佳解决方案是什么。

导航条码

import React, { Component } from "react";
import jwt_decode from "jwt-decode";
import { Link, withRouter } from "react-router-dom";

class Navbar extends Component {
  logOut(event) {
    event.preventDefault();
    localStorage.removeItem("usertoken");
    this.props.history.push("/login");
  }
  render() {
    return (
      <ul style={navBarStyle} id="sidenav-1" className="sidenav sidenav-fixed">
        <li>
          <h1 className="center-align" style={{ fontSize: "30px" }}>
            Hello
          </h1>
        </li>
        <li>
          <Link to="/profile">
            <i style={linkStyle} className="material-icons ">
              person
            </i>
          </Link>
        </li>
        <li>
          <a href="https://twitter.com/MaterializeCSS" target="_blank">
            <i style={linkStyle} className="material-icons ">
              book
            </i>
          </a>
        </li>
        <li>
          <Link to="/searchcourse">
            <i style={linkStyle} className="material-icons">
              search
            </i>
          </Link>
        </li>
        <li style={linkStyle}>
          <a href="" onClick={this.logOut.bind(this)}>
            <i style={linkStyles} className="fas fa-sign-out-alt" />
          </a>
        </li>
      </ul>
    );
  }
}

主页

class Homepage extends Component {
  componentDidMount() {
    document.title = "Dashboard";
  }
  render() {
    return (
      <div>
        <Navbar />
        <div className="container">
          <div>
            <h3>Dashboard</h3>
            <hr />
          </div>
          <div className="col" />
        </div>
      </div>
    );
  }
}

这是我的 app.js

<BrowserRouter>
<Route path="/login" component={Login} />
          <Route path="/register" component={Register} />
          <Route path="/homepage" component={Homepage} />
          <Route exact path="/profile" component={Profile} />
          <Route exact path="/searchcourse" component={SearchHelper} />
          <Route exact path="/item" component={CourseItem} />
</BrowserRouter>

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    您可以使用嵌套路由。将主页特定的子路由保留在主页组件中。这样路由/homepage 将打开主页组件。

    在主页内,您可以拥有导航栏和主页的子路由,例如:

    /homepage/profile/homepage/item

    这里有一篇文章要深入挖掘:https://medium.com/@marxlow/simple-nested-routes-with-layouts-in-react-router-v4-59b8b63a1184

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2020-03-04
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      相关资源
      最近更新 更多