react-admin动态加载资源后如何实现侧边栏菜单自动更新?
解决方案
你遇到的问题本质是react-admin的AdminUI仅会在初始化阶段从子组件中提取Resource信息注册到全局store,后续Resource列表更新时不会自动触发store同步,因此依赖store资源列表渲染的侧边栏菜单不会感知到变化。登出后资源残留也是因为旧的资源注册信息没有从store中清除。
具体修改步骤
- 移除你代码中占位用的空
<Resource />组件,该组件会干扰初始资源注册逻辑。 - 手动通过store dispatch方法同步资源列表,保证store和实际渲染的资源一致:
import { useDispatch, useNotify } from 'react-admin'; import { useEffect, useState } from 'react'; function AsyncResources() { const [resources, setResources] = useState([]); const dispatch = useDispatch(); const notify = useNotify(); // 替换为你从Hasura/后端拉取当前用户专属资源列表的逻辑 const fetchUserResources = async () => { try { const userResources = await fetchCurrentUserResources(); setResources(userResources); } catch (e) { notify('资源加载失败', { type: 'error' }); } }; // Auth0登录状态变更时重新拉取资源 useEffect(() => { // 替换为你的Auth0登录状态判断逻辑,比如判断user是否存在 if (isAuthenticated) { fetchUserResources(); } }, [isAuthenticated]); // 资源列表变更时同步更新全局store useEffect(() => { // 先清空旧的资源注册信息 dispatch({ type: 'RA/RESOURCE/UNREGISTER_ALL', }); // 批量注册新资源 resources.forEach(resource => { dispatch({ type: 'RA/RESOURCE/REGISTER', payload: { name: resource.name, options: getOptions(resource.name), list: getList(resource.name), // 如有create/edit/show等视图可在此补充 }, }); }); }, [resources, dispatch]); // 登出时清空本地资源列表和store注册信息 useEffect(() => { const handleLogout = () => { setResources([]); dispatch({ type: 'RA/RESOURCE/UNREGISTER_ALL', }); }; // 绑定Auth0登出事件回调 auth0.on('logout', handleLogout); return () => auth0.off('logout', handleLogout); }, [dispatch]); return ( <AdminUI title="Hasura Dashboard" dashboard={Dashboard} history={history} loginPage={LoginPage} layout={Layout} > {resources.map(resource => ( <Resource name={resource.name} key={resource.name} options={getOptions(resource.name)} list={getList(resource.name)} /> ))} </AdminUI> ); }
- 如果你使用了自定义菜单,确保菜单是通过
useResourceList钩子从全局store拉取资源列表,而不是硬编码或者从组件props传入固定列表,默认的useResourceList是响应store变化的,只要store中资源更新,菜单会自动重渲染。
内容的提问来源于stack exchange,提问作者Marco
相关产品推荐
相关产品推荐

