keep-alive-comp
TypeScript icon, indicating that this package has built-in type declarations

0.1.4 • Public • Published

React Component keep-alive

English | 中文

Dependencies

React: 16.8.0+

Install

npm i keep-alive-comp

Usage

optional useStorage param("sessionStorage"/"localStorage"): maintain cache after refresh("beforeRouteLeave" has been called)

if using useStorage, Components need to be used with Suspense

// example\index.tsx
import configKeepAlive from 'keep-alive-comp';
 
// optional
configKeepAlive({ maxLength: 2, useStorage: 'sessionStorage' });
// example\Router.tsx
import React, { Suspense } from 'react';
import { HashRouter, Route, Switch } from 'react-router-dom';
import { lazy } from '@loadable/component';
import KeepAlive from 'keep-alive-comp';
 
const List = lazy(() => import('./pages/list'));
const Detail = lazy(() => import('./pages/detail'));
 
const Router: React.FC = ({ children }) => (
  <HashRouter>
    {children}
    <Switch>
      <Route
        exact
        path="/"
        component={() => (
          <Suspense fallback={<div>loading...</div>}>
            <KeepAlive name="list">{(props) => <List {...props} />}</KeepAlive>
          </Suspense>
        )}
      />
      <Route
        exact
        path="/detail/:id"
        component={() => (
          <Suspense fallback={<div>loading...</div>}>
            <Detail />
          </Suspense>
        )}
      />
      <Route path="*" render={() => <h3>404</h3>} />
    </Switch>
  </HashRouter>
);
 
export default Router;

KeepAliveAssist

export interface KeepAliveAssist {
  beforeRouteLeave?: (scrollTopnumber, stateany) => void;
  scrollRestore?: () => number | null;
  stateRestore?: () => any;
  deleteCache?: () => void;
  getKeepAlive?: () => void;
}

Component Example

component: list

Readme

Keywords

Package Sidebar

Install

npm i keep-alive-comp

Weekly Downloads

3

Version

0.1.4

License

ISC

Unpacked Size

18.4 kB

Total Files

9

Last publish

Collaborators

  • zero9527