首页 > 解决方案 > react redux firebase中的私有路由不起作用

问题描述

我一直在尝试将 react-redux-firebase 与我的 react 应用程序集成。除了受保护的路线外,一切正常

我从 react-react-firebase 复制了私有路由的代码。

这是我的私人路线的代码

import React from "react";
import { Route, Redirect } from "react-router-dom";
import { useSelector } from "react-redux";
import { isLoaded, isEmpty } from "react-redux-firebase";

// A wrapper for <Route> that redirects to the login
// screen if you're not yet authenticated or if auth is not
// yet loaded
function PrivateRoute({ children, ...rest }) {
  // FIXME: #27 Imp This is not working for some reason, you can still access the not accessible locations
  const auth = useSelector((state) => state.firebase.auth);
  console.log(auth);
  console.log("Empty?");
  console.log(isEmpty(auth));
  console.log("Load?");
  console.log(isLoaded(auth));
  return (
    <Route
      {...rest}
      render={({ location }) =>
        // FIXME: Here it even if it is false it is rendering the children for some reason
        isLoaded(auth) && !isEmpty(auth) ? (
          // auth.uid==undefined ? ( // Even this does not work
          children
        ) : (
          <Redirect
            to={{
              pathname: "/redirect/login",
              state: { from: location },
            }}
          />
        )
      }
    />
  );
}

export default PrivateRoute;

即使 isEmpty 为假,它也会返回孩子。

这是我的减速器代码。

import { combineReducers } from "redux";
import { firebaseReducer } from "react-redux-firebase";

export default combineReducers({
  firebase: firebaseReducer,

  // authReducer,
  // apiStatusReducer,
});

在过去的 1 周里,我一直在尝试解决它,并且希望得到任何关于它为什么不起作用的帮助或提示。谢谢您的帮助。

编辑:-

出于某种奇怪的原因,即使交换孩子和重定向位置也有效。

<Route
      {...rest}
      render={({ location }) =>
        // FIXME: Here it even if it is false it is rendering the children for some reason
        isLoaded(auth) && isEmpty(auth) ? (
          // auth.uid==undefined ? ( // Even this does not work
          <Redirect
            to={{
              pathname: "/redirect/login",
              state: { from: location },
            }}
          />
        ) : (
          children
        )
      }
    />

标签: reactjsreduxreact-reduxfirebase-authenticationreact-redux-firebase

解决方案


截至 2020 年 9 月 16 日,这是 react-redux-firebase 存储库中的一个未解决问题(链接到问题)。@zachlyoung 提供了针对此问题的丑陋解决方法

通常,我们会以这种方式登录:

firebase.login(credentials).then(() => {
  props.history.push("/dashboard"); // Private Route
});

我们没有直接进入私有路由,而是再次更新 a​​uth。

firebase.login(credentials).then(() => {
  firebase.reloadAuth().then(() => {
    props.history.push("/dashboard"); // Private Route
  });
});

推荐阅读