反应路由器显示根组件以及路由路径

时间:2019-09-20 14:28:14

标签: javascript reactjs react-router

我目前是React的新手,并尝试使用React Router。但是我有一个问题,其中显示了顶层组件以及路径中的组件。在我的App.js中,我有一个Dashboard组件,该组件具有NavBar组件,并且路由器也位于该组件上。

这是我的仪表板组件

import React, { Component } from "react";
import { adalApiFetch } from "../config/adal-config";
import NavBar from "./NavBar";

export default class Dashboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isData: false,
      data: []
    };
    this.postToBackEnd = this.postToBackEnd.bind(this);
  }

  fetchData = () => {
    adalApiFetch(fetch, "/g2", {})
      .then(response => response.json())
      .then(responseJson => {
        if (!this.isCancelled) {
          this.setState({ isData: true, data: responseJson });
        }
      })
      .catch(error => {
        console.error(error);
      });
  };

  componentDidMount() {
    this.fetchData();
  }

  postToBackEnd() {
    adalApiFetch(fetch, "/sendEmail", {
      method: "post",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        username: this.state.data.username,
        email: this.state.data.email
      })
    })
      .then(response => response.json())
      .then(responseJson => {
        console.log(responseJson);
      })
      .catch(error => {
        console.error(error);
      });
  }

  render() {
    const { data, isData } = this.state;

    let spinner = (
      <strong className="c-spinner" role="progressbar">
        Loading…
      </strong>
    );

    return (
      <div>
          <header>
            <NavBar username={data.username} user_id={data.id} />
          </header>
        {isData ? (
          <div>

            <div className="o-container">
              <p className="c-heading-alpha u-margin-bottom-none">
                Wifi Maintenance Notifications
              </p>
              <p className="c-heading-delta u-margin-bottom"></p>
            </div>
            <div className="o-container">
              <article className="c-tile">
                <div className="c-tile__content">
                  <div className="c-tile__body u-padding-all">
                    <button
                      className="c-btn c-btn--primary"
                      onClick={this.postToBackEnd}>
                      Post
                    </button>
                  </div>
                </div>
              </article>
            </div>
          </div>
        ) : (
          <div className="o-container">{spinner}</div>
        )}
      </div>
    );
  }
}

这是我的NavBar组件

import React, { Component } from "react";
import { logOut } from "../config/adal-config";
import "./styles/NavBar.scss";
import {
  BrowserRouter as Router,
  Route,
  NavLink,
  Switch
} from "react-router-dom";
import Dashboard from "./Dashboard";
import Account from "./Account";
import History from "./History";


export default class NavBar extends Component {
  onLogOut() {   
    logOut();
  }

  render() {
    return (
      <Router>
        <div className="Header-navbar">
          <ul>
            <li>
              <NavLink exact to="/">
                Home
              </NavLink>
            </li>
            <li>
              <NavLink exact to="/history">
                History
              </NavLink>
            </li>
            <li>
              <NavLink exact  to="/account">
                Account
              </NavLink>
            </li>
            <li>
              <NavLink exact to="/logout" onClick={() => this.onLogOut()}>
              logout
              </NavLink>
            </li> 
            <li>{this.props.username}</li>
          </ul>
          <Switch>
            <Route exact path="/" component={Dashboard} />
            <Route  exact path="/history" render={() => <History/>} />
            <Route  exact path="/account" render={() => <Account/>} />
          </Switch>
          <p hidden>{this.props.user_id}</p>
        </div>
      </Router>
    );
  }
}

“历史记录和帐户”组件仅具有一个简单的H1标签。每当我导航到这些组件时,我的仪表板组件也会被加载。不知道我在做什么错。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

您正在NavBar组件内部渲染Dashboard,这就是为什么您也不断看到该组件的原因。尝试从NavBar组件中删除Dashboard,并将其用作应用程序的入口点。

要进一步详细说明,请从信息中心删除此部分:

 return (
      <div>
          /* Remove these lines
           *<header>
           *  <NavBar username={data.username} user_id={data.id} />
           *</header>
           */
        {isData ? (

只需渲染Navbar,如下所示:

render(<NavBar />, document.getElementById('root'))

查看此StackBlitz link 以获取有效示例。