如何根据用户Redux状态有条件地呈现Login或Dashboard ?



这是我的代码:

// Components 
import Dashboard from './Dashboard'; 
import Login from './Authentication/Login'; 
import { Route } from "react-router-dom";
// Redux import { useSelector, useDispatch } from 'react-redux'; 
import { selectUser } from '../userSlice';
function Authentication() {
// Redux to manage user state
var user = useSelector(selectUser); // Use the userReducer called "user"
return (
<>
{user ? <Dashboard /> : <Login />}
</>
)
}
export default Authentication;

这是我的商店和我的切片:

import { configureStore } from '@reduxjs/toolkit'; 
import userReducer from './userSlice';
export default configureStore({ 
reducer: { 
user: userReducer, 
}, 
});
import { createSlice } from "@reduxjs/toolkit";
const initialState = { user: null, };
export const userSlice = createSlice({ 
name: "user", 
initialState, 
reducers: { 
login: (state, action) => { state.user = action.payload; }, 
logout: (state) => { state.user = null; } }, 
}
);
export const { login, logout } = userSlice.actions;
export const selectUser = (state) => state.user.user; 
export default userSlice.reducer;

然而,我不确定这是否是最好的方法。我想确保,如果user state为null,那么我们去登录,否则我们去仪表板。

这是我的登录码:

// Imports
import react from 'react'
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import jwt_decode from "jwt-decode";
// Redux
import { useSelector, useDispatch } from 'react-redux';
import { login, selectUser } from '../../userSlice';

// Styling
import Container from '@mui/material/Container';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
// Google O-Auth
import { GoogleLogin } from 'react-google-login';
import Signup from './Signup';
const clientID = "743792005372-l001hnasupsvimqur3hq32pe8ngje3rr.apps.googleusercontent.com"
function Login() {
// Step 1: Add O-Auth functionality 
// Step 2: Add onClick functionality after submission 
// Step 3: Add useNavigate hook from React Router to redirect to user-specific Dashboard

// Redux to manage user state
const user = useSelector(state => state.user); // Use the userReducer called "user"
const dispatch = useDispatch(); // Use the dispatch function to update the userReducer
// const [ user, setUser ] = useState({});
const navigate = useNavigate();

function handleCallbackResponse(response) {
var userObject = jwt_decode(response.credential);
console.log("User logged in successfully!");
console.log(userObject);
// Use Redux to set state of user
dispatch(login(userObject)); // Here, login is the action and userObject is the action.payload 
navigate('/dashboard');
}
useEffect(() => {
/*global google*/
google.accounts.id.initialize({
client_id: clientID,
callback: handleCallbackResponse
});
google.accounts.id.renderButton(
document.getElementById('signInButton'),
{ theme: 'outline', size: 'large', type: 'standard' }
);
}, []);

return (
<Container align="center" sx={{ mt: '2rem' }}>
<Typography variant="h3">Welcome to</Typography>
<Typography variant="h1">ReadHub</Typography>

<Box id="signInButton" sx={{ m: 4 }}>
{/* <GoogleLogin
clientId={clientID}
buttonText={"Login"}
onSuccess={onSuccess}
onFailure={onFailure}
cookiePolicy={'single_host_origin'}
isSignedIn={true}
/> */}
</Box>

</Container>
);
}
export default Login;

现在,问题是:在重新加载时,转到根路由("/"),这是身份验证组件被呈现的地方,期望的行为是-如果登录,然后重定向到仪表板。然而,我只是得到一个带有模糊错误的白屏" Login component"。

在我看来,你必须添加一个状态属性,在这将有三种可能的状态,'checking','authenticated''not-authenticated',你可以在你的userSlice中添加它,这将是'checking'的初始状态,当你完成用户的身份验证时,根据结果将其放置'authenticated''not-authenticated'

如果你不等待用户完成加载,登录屏幕将首先呈现,发生在你身上的事情将会发生。要纠正它,您只需要在组件中执行以下操作:

function Authentication() {
// Redux to manage user state
var user = useSelector( selectUser ); // Use the userReducer called "user"
var status = useSelector( selectStatus );
// status = 'not-authenticated'; // 'authenticated'; // 'not-authenticated';
if ( status === 'checking' ) {
return (
<Loading />
);
}
return (
<>
{
status === 'authenticated'
? <Dashboard />
: <Login />
}
</>
);
}
祝你一切顺利。我希望它能帮助你。

最新更新