useContext导致不必要的重新渲染

时间:2019-08-05 05:51:29

标签: javascript reactjs react-router react-hooks react-state

我在登录表单时遇到了重新渲染和内存泄漏的问题。目标是拥有一个组件,该组件检查上下文的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 };
};

Login.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>
  );
}

使用自定义组件来保护路线。这样做是为了保护路由并在令牌无效的情况下重定向到登录名。

App.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 } }} />
        )
      }
    />
  );
}

0 个答案:

没有答案
相关问题