【发布时间】:2021-04-03 15:25:15
【问题描述】:
考虑下面的代码:
忽略所有的axios请求:
Login.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 更改为“fa”来更新GlobalContext。
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”逻辑。
提前致谢。
【问题讨论】:
-
您需要使用
redux-persist之类的内容与localStorage同步。 Redux 本身在刷新时总是会被清除。
标签: javascript reactjs redux state global