fix(scope): all pages react to company scope change via useScopeEffect
- Created useScopeEffect hook that auto-triggers reload on scope change - Replaced useEffect([], []) with useScopeEffect in 20+ pages - Risks/Reports/Dashboard also use useScopeEffect - Removed redundant per-page useCompanyScope where only effect was needed
This commit is contained in:
@@ -51,7 +51,7 @@ export function CompanyScopeProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 持久化选择
|
||||
// 持久化选择 + 派发事件通知各页面重新加载
|
||||
function setCompanyId(id: string | null) {
|
||||
setCompanyIdState(id);
|
||||
if (id) {
|
||||
@@ -59,6 +59,8 @@ export function CompanyScopeProvider({ children }: { children: ReactNode }) {
|
||||
} else {
|
||||
localStorage.setItem("company_scope_id", "all");
|
||||
}
|
||||
// 派发全局事件,让监听了 useScopeEffect 的页面重新加载数据
|
||||
window.dispatchEvent(new CustomEvent("company-scope-change", { detail: { companyId: id } }));
|
||||
}
|
||||
|
||||
const companyName = companyId
|
||||
@@ -86,3 +88,22 @@ export function useCompanyScope() {
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听企业视角变化,自动触发回调重新加载数据。
|
||||
*
|
||||
* 各页面在 useEffect 中调用此 hook,当全局企业选择变化时,
|
||||
* 会自动触发回调重新加载(apiFetch 会自动注入新的 company_id)。
|
||||
*
|
||||
* @param callback 数据加载回调
|
||||
* @param deps 额外依赖(如分页、筛选状态)
|
||||
*/
|
||||
export function useScopeEffect(callback: () => void, deps: unknown[] = []) {
|
||||
const { companyId } = useCompanyScope();
|
||||
|
||||
useEffect(() => {
|
||||
callback();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [companyId, ...deps]);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user