webpack4+react+antd从零搭建React脚手架(三)-路由搭建
react-router 还是 react-router-dom?
在 React 的使用中,我们一般要引入两个包,react 和 react-dom,那么 react-router 和 react-router-dom 是不是两个都要引用呢?
非也,坑就在这里。他们两个只要引用一个就行了,不同之处就是后者比前者多出了 这样的 DOM 类组件。
因此我们只需引用 react-router-dom 这个包就行了。当然,如果搭配 redux ,你还需要使用 react-router-redux。
what is the diff between react-router-dom & react-router?
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const BasicExample = () => (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
</ul>
<hr />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</div>
</Router>
);
以上是文档中给出的一个例子的代码段;这里说几个注意点,以及项目中我所遇到的。
介绍
- 首先需要写入一个
Router
也就是BrowserRouter
。其只有一个子节点,不然必报错。如上面的代码里面只有一个div
。 - Link相当于
a
标签。但是也需要在<Route path="/topics" component={Topics} />
,订阅一下。不然跳转不到内容。 - 我在项目里使用的
Switch
,当然其也需要在Router
包裹之下。
<Switch>
<Route path="/home" component={Home} />
<Route exact path="/list/:id" component={List} />
{/* 404 */}
<Route component={NotFounded} />
</Switch>
这里主要是实现,当跳转a页面,但是a页面,没有设置,就直接跳转到404
页面。
上面还有传参方式,path="/***/:id"
,可以在目的页面通过props
获得。即this.props.match.params
。
4. react-router-dom
同时也封装好了,js的路由跳转事件。
- history
- location
- match
其中详细的将方法列出。这里写一个简单的例子。
import React from 'react'
import { Route, Switch, BrowserRouter, Link } from 'react-router-dom'
import { Button } from 'antd';
export default class NotFounded extends React.Component {
constructor(props) {
super(props)
this.state = {}
}
goBack() {
this.props.history.push('home')
}
render() {
return (
<div>
<Link to="/home">返回首页</Link>
<Button onClick={() => this.goBack()} type="primary">返回首页</Button>
<h1>404</h1>
</div >
)
}
}
还有很多方法,请见官方文档https://reacttraining.com/react-router/web/api/history
传递参数
this.props.history.push('list/3')
下载地址
写在最后:
<Router>
<Link to="/list">Topics</Link>
</Router>
<Router>
<Routes />
</Router>
在下面的Routes
里,已经将list注册好了,<Route exact path="/list/:id" component={List} />
;结果<Link to="/list">Topics</Link>
,跳转失败,然后又在上面的Router
有注册了一遍list,就可以跳转了。