一个前端,爱跑步、爱吉他、爱做饭、爱生活、爱编程、爱南芳姑娘,爱我所爱。世间最温暖又无价的是阳光、空气与爱,愿它们能带你去更远的地方。

  • 文章
  • 心情
  • 照片墙
  • 工具
  • 开发技术分享

    react-live-route(react的组件缓存)使用

    技术 184 2021-06-02 14:44

    开题:之前用了react-keeper但是有BUG(scroll的位置不准确,而且onscroll的事件也无法监听到),

    所以抛弃之!太了,

    于是乎,找到了react-live-router,完美解决我们的问题:

    下面是是使用方法:

    1.下载库:

    npm i react-live-route
    

    2.在外面的routes中配置使用

    不需要改变我们之前的router结构(比如我之前用的react-router-dom

    开箱即用!这也是我选择使用这个库的原因,

    import { Route, Redirect, withRouter, Switch } from "react-router-dom";
    import NotLiveRoute from "react-live-route";
    const LiveRoute = withRouter(NotLiveRoute);
    

    3.引入好了之后,可以直接添加在

    注意:需要添加在Switch之外,相当于另外单独写了一个缓存的路由组件

    需要缓存的路由的component也需要在LiveRoute中引用

      <div className="routerBox">
            <Suspense fallback={"加载中。。"}>
              <Switch>
                {/* 路由重定向 */}
                <Route
                  exact
                  path="/"
                  render={() => {
                    return <Redirect to={{ pathname: `/book` }} />;
                  }}
                />
                <Route path="/book" />
              </Switch>
              <LiveRoute
                path="/book"
                component={Index}
                alwaysLive={true}
                name="book"
                onHide={(location, match, history, livePath, alwaysLive) => {
                  console.log("hide hook tiggered");
                }}
                onReappear={(location, match, history, livePath, alwaysLive) => {
                  console.log("reappear hook tiggered");
                }}
              />
            </Suspense>
          </div>
    

    另外:关于livePath和alwaysLive两个属性的使用:

    livePath

    livePath 为需要隐藏的页面的路径,具体规则与 react-router 中的 Route 的 path props 一样,使用 component 或 render 来渲染路由对应的组件。

    livePath 也可以接受一个由上述规则的 string 类型对象组成的数组,如果数组中的任意一个 string 匹配则 livePath 匹配。例如:["/path1","/path2","/path3/:id"]

    LiveRoute 会在从 livePaht 匹配的路径返回 path 匹配的路径时冲渲染,在进入其他不匹配的路径时会直接卸载。

    例如:

    List 的路由会在 /list 下正常渲染,当进入 /user/:id 时会隐藏,当进入这两者以外的页面时会正常卸载。

    import LiveRoute from 'react-live-route'
    <LiveRoute path="/list" livePath="/user/:id" component={List}/>
    

    alwaysLive

    alwaysLive 和 livePath 差不都,区别是路由的组件会在第一次 mount 后在其他任何路径都不会再被卸载。

    例如:Modal 页面在第一次正常渲染之后,进入路径不匹配的页面时隐藏,而在 Modal 路径匹配时更新渲染。

    import LiveRoute from 'react-live-route'
    <LiveRoute path="/list" alwaysLive={true} component={Modal}/>
    

    注意存在的一个BUG:使用了react-live-route 路由缓存之后,再使用import lazy懒加载引入路由 会造成bug (缓存的路由 和其它的路由同时存在)

    大概的开箱使用说明就这么多 具体请参考git仓库里面的说明:https://github.com/fi3ework/react-live-route/blob/master/docs/README-zh.md