react-router
之前用 vue 开发时使用的是 vue-router,感觉大同小异,所以我一开始都没把 react-router 放在眼里,但是在实际使用过程中,啧啧,那叫一个打脸。不定时更新此文,记录容易遇到的坑。
基本使用就不多说了,建议直接看官方文档。react-router 文档。另外,特此说明: 文章都是我边学习边记录总结的,如果错误,欢迎指正,互相交流,共同进步!
注意点 1: Route 的 component 和 render
When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop (below).
以上是官方文档的解释,简单来讲就是,使用<Route path='/' component={xxx}/>
,它实际上是使用React.createElement()
根据传入的xxx
创建了新的组件。假如说xxx
组件需要从父组件中获取数据,那么直接使用 component 的方式,不会触发xxx
组件的 componentDidMount;如果改成内联<Route path='/' component={() => xxx}/>
,那么组件比对时 React.createElement 的 type 不是xxx
这个类,而是一个匿名函数,所以每次都等于重新生成新的组件而不是只进行更新。所以这个时候就要使用 render 了:<Route path='/' render={() => xxx}/>
。
render 的另一个作用就是把 Route 的 props 传递给组件 : The render prop function has access to all the same route props (match, location and history) as the component render prop:
// wrapping/composing
// you can spread routeProps to make them available to your rendered Component
function FadingRoute({ component: Component, ...rest }) {
return (
<Route
{...rest}
render={routeProps => (
<FadeIn>
<Component {...routeProps} />
</FadeIn>
)}
/>
);
}
ReactDOM.render(
<Router>
<FadingRoute path="/cool" component={Something} />
</Router>,
node
);
注意点 2: Route 的 exact 和 strict
- 只有 exact
<Route exact path='/one' component={One}>
匹配 /one 和 /one/,不在乎是否有尾斜杠。
- 只有 strict
<Route strict path='/one/' component={One}>
匹配 /one/ 以及 /one/two,但是不匹配/one。
- both exact and strict
<Route exact strict path='/one' component={One}>
只匹配 /one,就是 path 是啥,就是啥。