Reactjs和Redux:身份验证后简要呈现LoginForm组件

时间:2020-05-08 10:20:19

标签: reactjs authentication redux rendering aws-amplify

我正在使用AWS Amplify和社交媒体身份验证来开发一个小型应用程序。在加载应用程序时,我要做的第一件事就是使用UseEffect()检查当前用户。 但这似乎在我的逻辑上存在缺陷,因为一旦对用户进行身份验证,我应该看到:

<>
{" "}
<Navbar />
<Welcome />
<AddQuestion />
</>

但是一秒钟左右,我仍然看到LoginForm。理想情况下,我想使用用户状态(Redux)有条件地显示组件,但是我无法弄清楚为什么在切换到正确的组件集之前进行此渲染。

App.js:

import React, { useEffect, useState } from "react";
import { Hub } from "aws-amplify";
import { useDispatch, useSelector } from "react-redux";
import { logOut, getCurrentUserAsync, loadingChange } from "./features/auth/authSlice";
import "./App.css";
import LoginForm from "./components/LoginForm";
import Welcome from "./components/Welcome";
import AddQuestion from "./components/AddQuestion";
import Navbar from "./components/Navbar";
import { Route, Redirect } from "react-router-dom";
import LinearProgress from "@material-ui/core/CircularProgress";

function App() {
  const dispatch = useDispatch();
  const [appLoading, setAppLoading] = useState(true);
  const [isAuth, setisAuth] = useState(false);
  const stateAuth = useSelector((state) => state.auth.isAuthenticated);

  useEffect(() => {
    // dispatch(loadingChange(true));

    console.log("UseEffect has run");
    // Load the current User
    if (appLoading) {
      // set listener for auth events
      Hub.listen("auth", async (data) => {
        //   setImmediate(() => dispatch({ type: "LOADING" }));
        const { payload } = data;
        if (payload.event === "signIn") {
          dispatch(getCurrentUserAsync());
          // dispatch(getCurrentUserAsync());
        } else if (payload.event === "signOut") {
          dispatch(logOut());
        }
      });
      // we check for the current user unless there is a redirect to ?signedIn=true
      if (!window.location.search.includes("?signedin=true") && appLoading) {
        dispatch(getCurrentUserAsync());
      }
    }
    // return () => {
    //   console.log("CLEANING...");
    // };
    setAppLoading(false);
    // eslint-disable-next-line
  }, []);

  if (appLoading) {
    return <LinearProgress />;
  } else {
    return stateAuth ? (
      <>
        {" "}
        <Navbar />
        <Welcome />
        <AddQuestion />
      </>
    ) : (
      <LoginForm />
    );
  }
}

export default App;

0 个答案:

没有答案