考虑以下代码:
忽略所有axios请求:
登录.js
const login = async () => {
let newLogin = {
email,
password,
};
await axios
.post("http://localhost:5000/login", newLogin)
.then((response) => {
if (response.data === 404) {
setUserError("User not found. Please Sign Up");
} else if (response.data === 403) {
setPasswordError("Incorrect Password");
} else {
dispatch({type:'LOG_IN',payload:{LoggedIn:true , currentUser:"Curent user"}})
navigate("/");
}
})
.catch((err) => console.log(err));
};
该页面通过将loggedIn更改为true和currentUser更改为"true"来更新GlobalContext;fa";。
Profile.js
import React , {useContext} from 'react'
import '../App.css'
import {Context} from '../GlobalState/Store'
const Profile = () => {
const [state,dispatch] = useContext(Context);
console.log(state);
return (
<div className="profile-page">
<div className="personal">
<h2>First Name:</h2>
<h2>Last Name:</h2>
<h2>Resistered Email:</h2>
<h2>User Name:</h2>
</div>
<div className="info">
<h2>Father Name:</h2>
<h2>Gender:</h2>
<h2>CNIC:</h2>
<h2>Blood Group:</h2>
<h2>Contact:</h2>
</div>
<div className="uni-info">
<h2>Designation:</h2>
<h2>Department:</h2>
<h2>Batch:</h2>
<h2>Roll No:</h2>
<h2>Enrolement:</h2>
</div>
</div>
);
}
export default Profile
这会获取状态并将其记录下来。
以下是Reducer.js和GlobalContext.js:
const Reducer = (state,action) =>{
switch(action.type){
case 'LOG_IN':
return {
userEmail: action.payload.currentUser,
loggedIn: action.payload.LoggedIn
}
case 'LOG_OUT':
return {
userEmail: action.payload.currentUser,
loggedIn: action.payload.LoggedIn
}
default:
return state;
}
}
export default Reducer;
import React,{useReducer , createContext} from 'react'
import Reducer from './Reducer';
const initialState ={
loggedIn: false,
currentUser:''
}
const Store = ({children}) => {
const [state , dispatch] = useReducer(Reducer,initialState)
return (
<Context.Provider value={[state , dispatch]} >
{children}
</Context.Provider>
)
}
export const Context = createContext(initialState)
export default Store
一切都运行得很好,一旦我登录,我就会按照预期重定向到主页,并记录正确的状态。
但一旦我在主页上刷新,一切都会恢复到初始状态。
我需要保留状态,因为它将用于应用"IfLoggedIn"逻辑。
提前谢谢。
Cookie时间(本地存储(
您的登录请求将为您的网站提供一个应存储的cookie。在进行任何操作之前加载页面时,请检查cookie/会话是否有效,并相应地设置状态。
您的反应状态不能(直接(在硬刷新之间保持