简体   繁体   中英

React context keep resetting

I have this file that contains all of my global routing / global state.

import React, { useEffect, useState, useContext } from "react";
import ReactDOM from 'react-dom';



const globalState = {
  email: null,
  token: null
};

export const  AuthContext = React.createContext(globalState);

function Routing() {

  const [currentUser, setCurrentUser] = useState(globalState);
  return (
    <AuthContext.Provider value={[currentUser, setCurrentUser]}>

      </AuthContext.Provider>
    );
}

ReactDOM.render(<Routing />, document.getElementById("app"));      
serviceWorker.unregister();

The thing is when I try to log out with this function the global state changes for about 3 seconds and it resets again."The user gets logged in again automatically".

const [user, setUser] = useContext(AuthContext);

const logOut = () => {
    setUser({email: null, token:null})

  }

I tried to look if there is any special way to change the global context but I didn't find anything.

How to stop the re-login "re-change of the state" of the AuthContext "Global state"

Here is my login

const login = e => {
    const form = document.getElementById('loginForm');
    e.preventDefault();
      setInterval(() => {
        setUser({email, token});
      }, timeOut);
    })
 }

Your code does not demonstrate what you describe, here is your code and I don't see it logging out magically after 3 seconds so you must have done something wrong somewhere else:

 const { useState, useContext } = React; const globalState = { email: null, token: null, }; const AuthContext = React.createContext(globalState); const LoginOut = () => { const [user, setUser] = useContext(AuthContext); const logOut = () => { setUser({ email: null, token: null }); }; const login = () => { setUser({ email: 'hi', token: 123 }); }; return user.email? ( <button onClick={logOut}>log out {user.email}</button> ): ( <button onClick={login}>log in</button> ); }; function Routing() { const [currentUser, setCurrentUser] = useState( globalState ); return ( <AuthContext.Provider value={[currentUser, setCurrentUser]} > <LoginOut /> </AuthContext.Provider> ); } ReactDOM.render( <Routing />, document.getElementById('root') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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