采用:react-activation
import KeepAlive from 'react-activation';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>count: {count}</p>
<button onClick={() => setCount((count) => count + 1)}>Add</button>
</div>
);
}
const Welcome: React.FC = () => {
const intl = useIntl();
const [show, setShow] = useState(true);
return (
<div>
<button onClick={() => setShow((show) => !show)}>Toggle</button>
<div>有KeepAlive</div>
{show && (
<KeepAlive>
<Counter />
</KeepAlive>
)}
<div>无KeepAlive</div>
{show && <Counter />}
</div>
);
};
export default Welcome;
入口app.tsx: childrenRender中使用
childrenRender: (children, props) => {
// if (initialState?.loading) return <PageLoading />;
return (
<AliveScope>
{children}
{!props.location?.pathname?.includes('/login') && (
<SettingDrawer
disableUrlParams
enableDarkTheme
settings={initialState?.settings}
onSettingChange={(settings) => {
setInitialState((preInitialState) => ({
...preInitialState,
settings,
}));
}}
/>
)}
</AliveScope>
);
},
我的调研:
React 页面间保存恢复状态的几种方法总结
umi使用umi-plugin-keep-alive实现页面缓存功能