我是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'));
答案 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
将呈现仅与确切路径匹配的路由