如何在reactjs中使用react-router

时间:2018-11-10 12:15:48

标签: javascript reactjs react-router

我是Reactjs的新手,我想使用路由器但不工作,显示空白页面。

如何使用路由器的Home类别和产品。我在App.jsx和index.jsx中放入了代码,但显示空白页,该如何解决。

以下是我的App.jsx代码

/* Import statements */
import React, { Component } from 'react';
import { Link, Route, Switch } from 'react-router-dom';

/* Home component */
const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
)

/* Category component */
const Category = () => (
  <div>
    <h2>Category</h2>
  </div>
)

/* Products component */
const Products = () => (
  <div>
    <h2>Products</h2>
  </div>
)

/* App component */
class App extends React.Component {
  render() {
    return (
      <div>
        <nav className="navbar navbar-light">
          <ul className="nav navbar-nav">

           /* Link components are used for linking to other views */
            <li><Link to="/">Homes</Link></li>
            <li><Link to="/category">Category</Link></li>
            <li><Link to="/products">Products</Link></li>

          </ul>
         </nav>

          /* Route components are rendered if the path prop matches the current URL */
           <Route path="/" component={Home}/>
           <Route path="/category" component={Category}/>
           <Route path="/products" component={Products}/>

      </div>
    )
  }
}

这是我的index.jsx代码

import React from 'react';
import { render } from 'react-dom';

import { App } from './components/App';
import './style.less';

render(<App />, document.getElementById('container'));

1 个答案:

答案 0 :(得分:0)

您需要导入BrowserRouter并将整个应用程序代码包装到该组件中,以便路由可以响应url更改,因此在导入react-router-dom

import { BrowserRouter, Route, Link } from “react-router-dom”

return (
   <BrowserRouter>
   <div>
    <nav className="navbar navbar-light">
      <ul className="nav navbar-nav">

       /* Link components are used for linking to other views */
        <li><Link to="/">Homes</Link></li>
        <li><Link to="/category">Category</Link></li>
        <li><Link to="/products">Products</Link></li>

      </ul>
     </nav>

      /* Route components are rendered if the path prop matches the current URL */
       <Switch>
       <Route path="/" component={Home}/>
       <Route path="/category" component={Category}/>
       <Route path="/products" component={Products}/>
       </Switch>

  </div>
  </BrowserRouter>
)

这样做,您将得到一个可行的示例,因此BrowserRouter将侦听对url所做的更改,并对更改到其Route组件中的更改做出反应,请记住,您需要传递给每个Route组件称为exact={true}的属性,甚至最好用Route组件包装您所有的Switch组件,以防止在完成更改URL后显示所有Route,而Switch将呈现仅与确切路径匹配的路由