React 利用useKeepState实现路由缓存

2020-06-04 · xiejiahe

这里不过多介绍,具体请查看: https://github.com/mousejs/use-keep-state

Demo 点击这里

useKeepState 是什么

利用 React Hooks 思想实现的一种类路由缓存方案, 实际上它是一种状态。

类似 Vue keep-alive 组件,但实际上不是组件,只是一个 hooks 状态。

有了 useKeepState , useState / useReducer 都可以不要了。因为它很简单,和 this.setState 非常像:

这是一个典型的例子:

import React from 'react';
import useKeepState from 'use-keep-state';

const namespace = 'App';
const initState = {
    name: 'name'
};

const App = () => {
  const [state, setState] = useKeepState(initState, namespace);

  const onClick = () => {
    setState({ name: 'Button' });
  };

  return (
    <div>
      <h1>{state.name}</h1>
      <button onClick={onClick}>Click</button>
    </div>
  )
}

export default App;

缺点是只能用在函数组件, 不适用 class

React
原创文章,转载请注明出处。