Reactjs 如何确保使用身份验证重定向更改状态?

Reactjs 如何确保使用身份验证重定向更改状态?,reactjs,redirect,axios,frontend,Reactjs,Redirect,Axios,Frontend,我的代码是一个前端,使用axios从API发出请求。 它检查cookie以了解是否登录以进行身份验证,因此如果没有cookie,它将重定向到主页 const privaterote:FunctionComponent=({ 组件:组件, 路径 }:AuthProps)=>{ const[isAuth,setisAuth]=useState(false); useffect(()=>{ axios .get('http://localhost:5000/api/v1/checkcookie', {

我的代码是一个前端,使用axios从API发出请求。 它检查cookie以了解是否登录以进行身份验证,因此如果没有cookie,它将重定向到主页

const privaterote:FunctionComponent=({
组件:组件,
路径
}:AuthProps)=>{
const[isAuth,setisAuth]=useState(false);
useffect(()=>{
axios
.get('http://localhost:5000/api/v1/checkcookie', {
事实上,
})
。然后((响应)=>{
setisAuth(response.data.cookie);
});
});
返回(
{
返回isAuth==true?:;
}}
/>
);
};
常量应用程序:React.FC=()=>{
返回(
);
};
但是,API发出请求后,
isAuth
状态将更改,但在以下情况下不会更改:

isAuth===true?:;
我只想确保它具有最后一个
isAuth
值。
如何确保它在进入状态之前更改状态?

尝试添加加载状态

补充说明:

您将需要catch来处理错误

添加一个空的deps数组以确保它只运行一次

const PrivateRoute: FunctionComponent<AuthProps> = ({
  component: Component,
  path,
}: AuthProps) => {
  const [isLoading, setIsLoading] = useState(true);
  const [isAuth, setisAuth] = useState(false);

  useEffect(() => {
    setIsLoading(true);
    axios
      .get('http://localhost:5000/api/v1/checkcookie', {
        withCredentials: true,
      })
      .then((response) => {
        setisAuth(response.data.cookie);
      })
      .catch(console.log)
      .finally(() => {
        setIsLoading(false);
      });
  }, []);

  if (isLoading) {
    return <></>;
  }

  return (
    <Route
      render={() => {
        return isAuth === true ? <Component /> : <Redirect to="/" />;
      }}
    />
  );
};
const privaterote:FunctionComponent=({
组件:组件,
路径
}:AuthProps)=>{
const[isLoading,setIsLoading]=useState(true);
const[isAuth,setisAuth]=useState(false);
useffect(()=>{
设置加载(真);
axios
.get('http://localhost:5000/api/v1/checkcookie', {
事实上,
})
。然后((响应)=>{
setisAuth(response.data.cookie);
})
.catch(console.log)
.最后(()=>{
设置加载(假);
});
}, []);
如果(孤岛加载){
返回;
}
返回(
{
返回isAuth==true?:;
}}
/>
);
};

response.data.cookie
布尔值吗?例如,如果
response.data.cookie='32094jwef9u23sdkf'
,则
isAuth===true
将永远不会计算
true
,重定向将始终呈现。此外,通常更正确的做法是,不要直接针对
true
false
进行测试,只需使用变量值的javascript truthy/false即可

检查react路由器dom示例

这里需要注意的是,auth检查在
render
prop中。原因是当呈现
路由器
时,专用路由将只呈现一次,但匹配的路由将在必要时呈现/重新呈现其子级

  • 尝试将身份验证检查移动到
    渲染
    属性中
  • 添加加载状态并在身份验证检查挂起时返回null,使用
    。最后
    块发出不加载的信号
  • 如果cookie存在或不存在,请保存布尔值
    isAuth
  • 代码:

    const privaterote:FunctionComponent=({
    组件:组件,
    路径
    }:AuthProps)=>{
    返回(
    {
    const[isAuth,setIsAuth]=useState(false);
    const[loading,setLoading]=useState(false);
    useffect(()=>{
    设置加载(真);
    axios
    .get('http://localhost:5000/api/v1/checkcookie', {
    事实上,
    })
    。然后((响应)=>{
    setIsAuth(!!response.data.cookie);
    })
    .最后(()=>setLoading(false));
    }, []);
    if(加载)返回null;
    返回isAuth?:;
    }}
    />
    );
    };
    
    const PrivateRoute: FunctionComponent<AuthProps> = ({
      component: Component,
      path,
    }: AuthProps) => {
      return (
        <Route
          render={(routeProps) => {
            const [isAuth, setIsAuth] = useState(false);
            const [loading, setLoading] = useState(false);
    
            useEffect(() => {
              setLoading(true);
              axios
                .get('http://localhost:5000/api/v1/checkcookie', {
                  withCredentials: true,
                })
                .then((response) => {
                  setIsAuth(!!response.data.cookie);
                })
                .finally(() => setLoading(false));
            }, []);
    
            if (loading) return null;
    
            return isAuth ? <Component {...routeProps} /> : <Redirect to="/" />;
          }}
        />
      );
    };