当用户是管理员时,单击视图按钮将把他重定向到/view
页,而如果用户不是管理员,则不显示该视图按钮也将限制用户通过键入以下内容来查看该页面URL /view
。
我从useGetUserquery
挂钩中获取了用户角色,并用它来检查是否渲染视图组件。
代码:
function Parent() {
return (
<>
<a href="/view">
<button>view</button>
</a>
</>
);
}
function useAnother() {
const { refetch: refetchItems } = useGetItems();
return async function () {
await refreshCompany();
refetchItems();
}
}
function Load() {
const [loaded, setLoaded] = React.useState(false);
const load = useAnother();
useEffect(() => {
if (loaded) return;
setLoaded(true);
load();
}, [loaded, setLoaded, load]);
}
function Child() {
useLoad();
const sso = getUser();
const { user: user } = useGetUserBySso(sso.id);
const admin = user.role === "admin";
return admin ? <View /> : <Redirect to="/" />
}
以上代码根据需要工作。但在以下情况下失败,
当用户角色为admin且位于/view
页中并且用户角色更改为非管理员时,除非刷新页面,否则用户仍位于/view
页中。
为解决此问题,我在useEffect
中重新吸引了用户,如下所示,
function useAnother() {
const { refetch: refetchItems } = useGetItems();
const sso = getUser(); //new code added
const { refetch: refetchUser } = useGetUserBySso(sso.id); // New code added
return async function () {
await refreshCompany();
refetchUser(); // Refetching user here
refetchItems();
}
}
function Load() {
const [loaded, setLoaded] = React.useState(false);
const load = useAnother();
useEffect(() => {
if (loaded) return;
setLoaded(true);
load();
}, [loaded, setLoaded, load]);
}
function Child() {
useLoad(); // Is it possible to get the user from the 'useAnother' to 'useLoad' and use it here?
const sso = getUser();
const { user: user } = useGetUserBySso(sso.id);
const admin = user.role === "admin";
return admin ? <View /> : <Redirect to="/" />
}
上面的代码也可以使用,但是我觉得useAnother
和Child组件的两个位置都使用了该用户变量。
有没有办法让这个用户从useAnother
到useLoad
并将其传递给子组件,或者换句话说,有没有办法可以简化此代码使其看起来更整洁?
注意:我刚接触useEffect
和useState
。