采用: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实现页面缓存功能
本文介绍了如何在React应用中使用react-activation库来实现页面间的状态保持,并探讨了KeepAlive组件在优化页面加载性能和组件复用中的作用。通过实例展示了如何在`Welcome`组件中结合`useState`和`KeepAlive`进行状态管理和页面缓存。
1011

被折叠的 条评论
为什么被折叠?



