单击<link />时,React Router 4.1.1无法渲染

时间:2017-05-07 20:37:21

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

我只是试图点击一个组件并反应重新呈现需要渲染的内容。但我根本无法存档。这就是我到目前为止所做的:

Index.js(这是我试图存储所有路线的地方)

import React from "react";
import ReactDOM from "react-dom";
import Main from "./pages/index/main.js";
import Login from "./pages/signin/signin.js";
import { BrowserRouter as Router, Route, Switch} from "react-router-dom";
ReactDOM.render(
  <div>
    <Router>
      <Switch>
        <Route exact  path="/" render={()=> <Main />}/>
        <Route path="/login" render={()=> <Login />}/>
      </Switch>
    </Router>
  </div>,
  document.getElementById("root")
);

Header.JS(我在其中设置了Link标签)

import React from "react";
import style from "./../acc/css/navbar.css";
import { BrowserRouter as Router, Link} from "react-router-dom";
export default class Header extends React.Component {
    render() {
        return (
            <Router>
    <section className={style.nav} id="nav">
            <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/login">Login</Link></li>
            </ul>
        </section>
        </Router>
        );
    }
}

截至目前,当我手动转到/时,它会呈现Main组件,当我手动转到/login时,它会呈现Login组件。

但是,当我点击<Link>组件时,它不会呈现,只会将网址更改为/login或反之亦然。

我想知道这个问题是否有任何解决方案?

编辑1

Main.js代码

import React from "react";
//import compunts
import Header from "./../header.js";
import Qoute from "./qoute.js";
import Grades from "./grades.js";

export default class Main extends React.Component {
    render() {
        return (
      <div id="continor">
                <Header />
                <Qoute />
                <Grades />
            </div>
        );
    }
}

Signin.js

    import React from "react";
    import Header from "./../header.js";
    import Qoute from "./qoute.js";
    import Form from "./form.js";
    export default class Login extends React.Component {
        render() {
            return(
          <div>
          <Header />
            <section id="info">
              <div className="containor">
                <div className="row">
                  <Qoute />
                  <Form />
                </div>
              </div>
            </section>
          </div>
            );
        }
    }

为了澄清,我试过了

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

但仍然无效。任何解决方案?

2 个答案:

答案 0 :(得分:0)

现在<Link>标记内有<Router>个元素。您必须删除此<Router>并且链接开始有效。

答案 1 :(得分:0)

尝试将您的Header.js更改为

import React from "react";
import style from "./../acc/css/navbar.css";
import { BrowserRouter as Router, Link} from "react-router-dom";
export default class Header extends React.Component {
    render() {
        return (
    <section className={style.nav} id="nav">
            <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/login">Login</Link></li>
            </ul>
        </section>
        );
    }
}

然后点击它显示的链接。