React 页面缓存 keep-Alive

官方推荐使用状态管理器来缓存页面。

  1. 搭建好状态管理器(这里用zustand );

React 页面缓存 keep-Alive_第1张图片
// index.tsx
import pageKeepAlive from './module/pageKeepAlive';

const store = {
  pageKeepAlive
}

export default store
// pageKeepAlive.ts
import create from 'zustand'
import { persist } from "zustand/middleware" // 持久化
let pageKeepAlive: any = (set: Function, get: Function) => ({
    pageList: {},
       /*
        预期结构:
            pageList:{
                page1:{
                    key:value,
                    key2:value
                },
                page2:{
                    key:value,
                    key2:value
                },
            }
        */
    setForKey: (key: string, data: any) => {
         // key值相同自动覆盖,在严谨一点需判断存在要删除
        set((state: { pageList: Object }) => ({ pageList: { ...state.pageList, [key]: data } }))
    },
    removeForKey:(key:string)=>{
        let list =  get().pageList[key]
        delete list[key];
        set({ pageList: list });
    },
    removeAll: () => {
        return new Promise((resolve: any, reject: any) => {
            localStorage.removeItem("pageKeepAlive-basket");
            resolve("removeKeepAlive Success!");
        })
    }
});
pageKeepAlive = persist(pageKeepAlive, { name: "pageKeepAlive-basket" });
export default create(pageKeepAlive);
  1. 读取值和写入值;

精简版
// your page
import store from '../../store'
import { useEffect, useState } from "react";
function Quill() {

//读取 pageList 中 quillPageValue 的内容;
const quillPageValue = store.pageKeepAlive(((state: { pageList: { quillPageValue: Object } }) => state.pageList.quillPageValue));

//读取后新声明参数给页面内使用
  const [quillValue,setquillValue] = useState(quillPageValue.reactQuillValue||"");

//声明set方法
  const setForKey = store.pageKeepAlive(((state: { setForKey: Function }) => state.setForKey));

// 监听 quillValue;卸载后触发
  useEffect(() => {
    return () => {
      setForKey("quillPageValue",{reactQuillValue:quillValue});
    }
  }, []);

  return (
          
      

刷新页面或切换会发现quillValue的值自动归位了

你可能感兴趣的:(react)