我如何在React中使用useEffect?

时间:2020-06-08 19:49:34

标签: reactjs typescript

当用户是管理员时,单击视图按钮将把他重定向到/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组件的两个位置都使用了该用户变量。

有没有办法让这个用户从useAnotheruseLoad并将其传递给子组件,或者换句话说,有没有办法可以简化此代码使其看起来更整洁?

注意:我刚接触useEffectuseState

0 个答案:

没有答案