Reactjs useContext值在页面刷新和注销期间被清除

Reactjs useContext值在页面刷新和注销期间被清除,reactjs,react-hooks,use-context,Reactjs,React Hooks,Use Context,更新配置文件时,profile.name通过navlink(Navigation.js)中的useContext()显示。但一旦页面刷新或注销时,profile.name就会被清除,同时,profile.photo也不会在navlink中显示 我想在导航链接中始终显示姓名和照片,我如何才能做到这一点 UserProfileProvider.js import React, { useMemo, useState} from 'react'; import UserProfileContext f

更新配置文件时,
profile.name
通过navlink(Navigation.js)中的
useContext()
显示。但一旦页面刷新或注销时,profile.name就会被清除,同时,
profile.photo
也不会在navlink中显示

我想在导航链接中始终显示姓名和照片,我如何才能做到这一点

UserProfileProvider.js

import React, { useMemo, useState} from 'react';
import UserProfileContext from '../context';

const UserProfileProvider = ({children}) => {

    const [profile, setProfile] = useState({ _id: '', photo: '', name: '', email:'', phonenumber:'', position:'', privilege:'', password:''});

    const value = useMemo(() => ({
        profile, setProfile
    }), [profile]);


    return (
       <UserProfileContext.Provider value={value}>
           {children}
       </UserProfileContext.Provider>
    )   
}
export default UserProfileProvider;
import React, { useContext } from 'react';
import { NavLink, useHistory } from 'react-router-dom';
import UserProfileContext from '../context';


const Navigation = () => {
    const history = useHistory();
    const {profile} = useContext(UserProfileContext); // added 16 jun based on stack

    const divStyle = {
        float:'left',
        color: '#64cad8', 
        padding: '0px 0px 0px 10px',
        font:'Lucida, sans-serif'
      };

    function logout() {
        localStorage.removeItem('loginEmail')
        localStorage.removeItem('Privilege')
        history.push('/login')
        window.location.reload(true);
      }

    return localStorage.getItem('loginEmail') &&
        <div className="App">
            <div className="wrapper">
                <div id="wrap">
                    <nav className="siteNavigation_nav_links">
                    <div className="clubLogo landing"style={divStyle}><b>Southside Soccer</b></div>
                        <NavLink className="mobile_register_link" to="/">Home</NavLink>
                        <NavLink className="mobile_register_link" to="/profile">Profile</NavLink>
                        <NavLink className="mobile_login_link" to="/login" onClick={logout}>Logout</NavLink>
                        <NavLink className="mobile_login_link" to='/aboutus'>About us</NavLink>
                        <span className="mobile_login_link">{profile.name}<img className="nav_profile"src={profile.photo}></img></span>
                    </nav>
                </div>
            </div>
        </div>
}

export default Navigation;
import UserProfileProvider from './components/UserProfileProvider.js';

var ReactDOM = require("react-dom");

const App = () => {                       // added 16 jun based on stack

  return (
  <BrowserRouter>
    <UserProfileProvider>
          <>
        <Navigation />
          <Switch>
              <ProtectedRoute exact path="/" component={Home} />
              <ProtectedRoute path="/profile" component={Profile} />
              <ProtectedRoute path="/aboutus" component={Aboutus} />
              <Route path="/register" component={Register} />
              <Route path="/login" component={Login} />
              <Route exact path="*" component={ErrorPage} />
          </Switch>
          </>
      </UserProfileProvider>
   </BrowserRouter>
  );
};
ReactDOM.render(
  React.createElement(App, null),
  document.getElementById("root")
);

export default App;
import React, {useContext, useEffect, useState } from "react";
import UserProfileContext from '../context';

const {profile, setProfile} = useContext(UserProfileContext);
...// rest of the Profile component code...
App.js

import React, { useMemo, useState} from 'react';
import UserProfileContext from '../context';

const UserProfileProvider = ({children}) => {

    const [profile, setProfile] = useState({ _id: '', photo: '', name: '', email:'', phonenumber:'', position:'', privilege:'', password:''});

    const value = useMemo(() => ({
        profile, setProfile
    }), [profile]);


    return (
       <UserProfileContext.Provider value={value}>
           {children}
       </UserProfileContext.Provider>
    )   
}
export default UserProfileProvider;
import React, { useContext } from 'react';
import { NavLink, useHistory } from 'react-router-dom';
import UserProfileContext from '../context';


const Navigation = () => {
    const history = useHistory();
    const {profile} = useContext(UserProfileContext); // added 16 jun based on stack

    const divStyle = {
        float:'left',
        color: '#64cad8', 
        padding: '0px 0px 0px 10px',
        font:'Lucida, sans-serif'
      };

    function logout() {
        localStorage.removeItem('loginEmail')
        localStorage.removeItem('Privilege')
        history.push('/login')
        window.location.reload(true);
      }

    return localStorage.getItem('loginEmail') &&
        <div className="App">
            <div className="wrapper">
                <div id="wrap">
                    <nav className="siteNavigation_nav_links">
                    <div className="clubLogo landing"style={divStyle}><b>Southside Soccer</b></div>
                        <NavLink className="mobile_register_link" to="/">Home</NavLink>
                        <NavLink className="mobile_register_link" to="/profile">Profile</NavLink>
                        <NavLink className="mobile_login_link" to="/login" onClick={logout}>Logout</NavLink>
                        <NavLink className="mobile_login_link" to='/aboutus'>About us</NavLink>
                        <span className="mobile_login_link">{profile.name}<img className="nav_profile"src={profile.photo}></img></span>
                    </nav>
                </div>
            </div>
        </div>
}

export default Navigation;
import UserProfileProvider from './components/UserProfileProvider.js';

var ReactDOM = require("react-dom");

const App = () => {                       // added 16 jun based on stack

  return (
  <BrowserRouter>
    <UserProfileProvider>
          <>
        <Navigation />
          <Switch>
              <ProtectedRoute exact path="/" component={Home} />
              <ProtectedRoute path="/profile" component={Profile} />
              <ProtectedRoute path="/aboutus" component={Aboutus} />
              <Route path="/register" component={Register} />
              <Route path="/login" component={Login} />
              <Route exact path="*" component={ErrorPage} />
          </Switch>
          </>
      </UserProfileProvider>
   </BrowserRouter>
  );
};
ReactDOM.render(
  React.createElement(App, null),
  document.getElementById("root")
);

export default App;
import React, {useContext, useEffect, useState } from "react";
import UserProfileContext from '../context';

const {profile, setProfile} = useContext(UserProfileContext);
...// rest of the Profile component code...

当然。因为react是客户端的,所以无论何时刷新数据都会丢失(contextAPI或任何状态管理)。您可以使用
useffect
componentDidMount
lifecycle在每次装载
App
component

时再次获取数据。好的,我应该在哪里再次使用
useffect()
。?我应该在Navigation.js中使用它吗?我还可以知道为什么没有
配置文件.photo
?对于全局状态,请在呈现子组件之前获取根组件上的用户数据,以确保数据始终可用提醒您,每当刷新时,所有状态都将丢失您是否打算在根组件ie上使用
useffect()
UserProfileProvider.js