简体   繁体   English

页面重新加载后保留 GlobalState

[英]Retain GlobalState after page reload

Consider the code below:考虑下面的代码:

Ignore all the axios request:忽略所有 axios 请求:

Login.js登录.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));
  };

This pages updates the GlobalContext by changing loggedIn to true and currentUser to "fa".此页面通过将loggedIn 更改为true 并将currentUser 更改为“fa”来更新GlobalContext。

Profile.js 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

This gets the state and logs it.这将获取 state 并记录它。

Here are the Reducer.js and GlobalContext.js :这是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

Everything works beautifully and once I log in, I'm redirected to homepage as I'm supposed to and the correct state is being logged.一切都很顺利,一旦我登录,我就会被重定向到我应该做的主页,并且正在记录正确的 state。

But once I refresh on the home page everything is reverted back to the initial state.但是一旦我在主页上刷新,一切都会恢复到最初的 state。

I need to retain the state as it will be used to apply the 'IfLoggedIn' logic.我需要保留 state,因为它将用于应用“IfLoggedIn”逻辑。

Thanks in advance.提前致谢。

Cookie time (local storage) Cookie时间(本地存储)

Your login request will give your site a cookie that should be stored.您的登录请求将为您的网站提供一个应该存储的 cookie。 when loading the page before anything check if the cookie/session is valid and set the state accoridingly.在加载页面之前检查cookie/会话是否有效并相应地设置state。

Your react state cannot be staved (directly) between hard refreshes您的反应 state 不能在硬刷新之间(直接)被搁置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM