在做项目的时候发现自己对路由的了解还不够,只会简单的一些东西,对于页面跳转和url重置导致的路由相关的匹配了解不多,所以写了这篇分享,说一说路由。
路由
路由就是用来保持我们的UI和URL相同步,可以正确的渲染页面,它拥有简单的 API 与强大的功能例如代码缓冲加载、动态路由匹配、以及建立正确的位置过渡处理。首先,可以通过npm安装react-router-dom,react-router-dom依赖于react-router,安装react-router-dom即可。
npm install react-router-dom --save
再在代码中引入< BrowserRouter >或者< HashRouter >路由,然后可以通过比较Route的path属性来匹配当前地址
//使用ES6语法导入
import { HashRouter, Route } from 'react-router-dom';
ReactDOM.render(
<HashRouter>
<Route path='/' component={FirstPage} />
</HashRouter>
,
app
)
分享几个使用比较多的场景
路由嵌套
//使用ES6语法导入
import { HashRouter, Route, IndexRoute } from 'react-router-dom';
ReactDOM.render(
<HashRouter>
<Route path='/' component={FirstPage}>
<IndexRoute component={Main} />
<Route path='title' component={FirstPageTitle} />
</Route>
</HashRouter>
,
app
)
使用IndexRoute可以使得当用户访问'/'时,FirstPage组件会被渲染,它的内部组件也会被渲染,父组件可以通过this.prop.children来渲染内部路由,如果不加上IndexRoute,FirstPage组件内部的this.props.children是为undefined的
路由重定向
//使用ES6语法导入
import { HashRouter, Route, Redirect } from 'react-router-dom';
ReactDOM.render(
<HashRouter>
<Route path='/firstPage' component={FirstPage} />
<Route path='/secondPage' component={SecondPage} />
<Redirect to='/firstPage' />
</HashRouter>
,
app
)
路由配置项onEnter,onLeave
在react-router v4版本之前,onEnter,onLeave是路由的钩子,路由会在页面跳转的时候触发这些钩子,在跳转页面的时候,钩子会在所有将离开的路由中触发,从最下层的子路由开始直到最外层父路由结束,比如在用户从/firstPage跳转到到/secondPage的时候,会先触发/firstPage的onLeave,再去触发/secondPage的onEnter
存取参数
在没有状态管理或者不想使用浏览器存储的情况下,可以通过路由将数据存储在url中,达到浏览器刷新后依旧可以获取到存储的值
//使用ES6语法导入
import { HashRouter, Route, Redirect } from 'react-router-dom';
ReactDOM.render(
<HashRouter>
<Route path='/firstPage' component={FirstPage} />
<Route path='/secondPage/:count?' component={SecondPage} />
<Redirect to='/firstPage' />
</HashRouter>
,
app
)
SecondPage组件可以通过this.props.history.push({ pathname: `/secondPage/${count}` }) 改变当前的url,在url中存参数count,同时也可以在this.props.match.params中取得参数
withRouter高级组件
//使用ES6语法导入
import { HashRouter, Route, Redirect, withRouter } from 'react-router-dom';
class ShowLocation extends Component {
render() {
const location = this.props.location
return(
<div>
pathname is {location.pathname}
{this.props.children}
</div>
)
}
}
const ShowLocationRouter = withRouter(ShowLocation)
ReactDOM.render(
<HashRouter>
<ShowLocationRouter>
<Route path='/firstPage' component={FirstPage} />
<Route path='/secondPage/:count?' component={SecondPage} />
<Redirect to='/firstPage' />
</ShowLocationRouter>
</HashRouter>
,
app
)
默认情况下必须通过路由匹配渲染的组件才存在this.props,location,match,当其他组件也需要使用这些路由参数时,可以通过withRouter高级组件包裹组件,传入路由参数。