react-router填坑记录

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

  1. 只有 exact
<Route exact path='/one' component={One}>

匹配 /one 和 /one/,不在乎是否有尾斜杠。

  1. 只有 strict
<Route strict path='/one/' component={One}>

匹配 /one/ 以及 /one/two,但是不匹配/one。

  1. both exact and strict
<Route exact strict path='/one' component={One}>

只匹配 /one,就是 path 是啥,就是啥。


Route 在实际开发中的应用

react-router 路由守卫与最佳实践

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yokiizx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值