【问题标题】:Wait for useContext Object in React在 React 中等待 useContext 对象
【发布时间】:2020-04-11 18:08:20
【问题描述】:

我正在尝试在 React 中设置 PrivateRouter,但我发现以下代码重定向到登录页面由于上下文变量为空,尽管 currentUser 对象存在。

有没有办法等待那些上下文变量或其他方法来解决这个路由问题?

import React, { useContext } from "react";
import { Route, Redirect } from "react-router-dom";
import { AuthContext} from "./Auth";

const PrivateRoute = ({ component: RouteComponent, ...rest }) => {

  const {currentUser} = useContext(AuthContext);

  return (
    <Route
      {...rest}
      render={routeProps =>
        !!currentUser ? (
          <RouteComponent {...routeProps} />
        ) : (
          <Redirect to={"/login"} />
        )
      }
    />
  );
};
export default PrivateRoute

【问题讨论】:

  • 你需要保持一个加载状态。您可以在 AuthContext 提供程序本身中拥有它

标签: reactjs


【解决方案1】:

我在这里回答:https://stackoverflow.com/a/63478324/9404135 另外,您可以查看该问题中的其他答案。

我今天遇到了这个问题,我喜欢 Shubham 的做法。但是我解决它的方法只是从前一个组件中获取userinfo 并将其传递给这个profile 组件。

但是,请确保像这样渲染 Profile 组件,以便确保 userinfo 存在:

function ParentComponent(){
 // do sth to get the userinfo here
return(
  <ParentComponent>
     {userinfo? <Profile userinfo={userinfo} /> : null}       
 <ParentComponent/>
)
}

【讨论】:

    猜你喜欢
    • 2020-09-12
    • 1970-01-01
    • 2021-08-09
    • 2016-01-17
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    相关资源
    最近更新 更多