首页 > 解决方案 > useContext 导致不需要的重新渲染

问题描述

我在登录表单中遇到了重新渲染和内存泄漏的问题。目标是有一个组件来检查上下文的 JWT 是否有效,如果有效则重定向。但是,当登录和更新上下文时,上下文在无论如何都应该重定向时会导致重新呈现。解决方案是什么?

编辑:问题似乎是我在身份验证上重新渲染了两次:一次在登录中,一次在 SecuredRoute 中。有没有更优雅的解决方案?

useValidateToken.js

export default token => {
  const [validateLoading, setLoading] = useState(true);
  const [authenticated, setAuthenticated] = useState(false);

  useEffect(() => {
    fetch(`/validate_token`, {
      method: "GET",
      headers: { Authorization: "Bearer " + token }
    })
      .then(resp => {
        if (resp.ok) setAuthenticated(true);

        setLoading(false);
      })
      .catch(_ => setLoading(false));
  }, [token]);

  return { validateLoading, authenticated };
};

登录.js

function Login(props) {
  const {token, setToken} = useContext(TokenContext)

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const { isLoading: validateLoading, authenticated } = useValidateToken(token);
  const [shouldRedirect, setShouldRedirect] = useState(false);

  const [isLoading, setIsLoading] = useState(false);
  const [isInvalid, setIsInvalid] = useState(false);

  function login() {
    setIsLoading(true);

    fetch(`/login`, { ... })
      .then(resp => resp.json())
      .then(body => {
        if (body.jwt) {
          setToken(body.jwt);
          setShouldRedirect(true);
        } else {
          setIsInvalid(true);
          setTimeout(function () { setIsInvalid(false) }, 3000)
          setIsLoading(false);
        }
      })
      .catch(_ => setIsLoading(false));
  }

  return validateLoading ? (
    // Skipped code
  ) : shouldRedirect === true || authenticated === true ? (
    <Redirect to={props.location.state ? props.location.state.from.pathname : "/"} />
  ) : (
    <div className="login">
      // Skipped code
        <LoginButton loading={isLoading} login={login} error={isInvalid} />
      </div>
    </div>
  );
}

Route 使用自定义组件进行保护。这样做是为了保护路由并在存在无效令牌时重定向到登录。

应用程序.js

// Skipped code
const [token, setToken] = useState(null);
const { authenticated } = useValidateToken(token)

//Skipped code
<SecuredRoute exact path="/add-issue/" component={AddIssue} authenticated={authenticated} />

function SecuredRoute({ component: Component, authenticated, ...rest }) {
  return (
    <Route
      {...rest}
      render={props =>
        authenticated === true ? (
          <Component {...props} {...rest} />
        ) : (
          <Redirect to={{ pathname: "/login", state: { from: props.location } }} />
        )
      }
    />
  );
}

标签: javascriptreactjsreact-routerreact-hooksreact-state

解决方案


推荐阅读