页面重新加载后保留 GlobalState

时间:2021-04-03 15:25:15

标签: javascript reactjs redux state global

考虑下面的代码:

忽略所有 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));
  };

此页面通过将 logined 更改为 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.jsGlobalContext.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”逻辑。

提前致谢。

1 个答案:

答案 0 :(得分:0)

Cookie 时间(本地存储)

您的登录请求将为您的网站提供一个应存储的 cookie。在加载页面之前,先检查 cookie/session 是否有效并相应地设置状态。

您的反应状态不能(直接)在硬刷新之间保持