所以下面的代码是我试图在localStorage
页面刷新之后保持用户状态的方式。
这基本上适用于主页,每当我刷新时,我都会看到localStorage
即使刷新确实仍然存在。但是,当我通过与网页交互并在该页面上刷新时,我会丢失localStorage
我通过 react useContext 函数传递用户状态(其设置器是 setUser)。有兴趣听听任何人的想法。谢谢!
import axios from 'axios'
import firebase from 'firebase/app';
import 'firebase/database';
import React, {useState, useContext, useEffect} from 'react';
import {Router } from 'react-router-dom'
import logo from './logo.svg';
import './App.css';
import Spotify from 'spotify-web-api-js';
import Homepage from './components/homepage';
import Login from './components/login'
import MapLeaflet from './components/MapLeaflet'
import {BrowserRouter, Route} from 'react-router-dom'
import Signup from './components/signup';
import ArtistPage from './components/artisthomepage'
import {dbMessages, dbPosts, dbSongs, dbArtists, dbReplies} from './firebase/firebase';
const s = new Spotify();
export const InfoContext = React.createContext();
function App() {
const [artists, setArtists]=useState("")
const [messages, setMessages]=useState("")
const [songs, setSongs]=useState("")
const [posts, setPosts]=useState("")
const [replies, setReplies]=useState("")
const [user, setUser]=useState("")
const [accesstoken, setAccesToken]=useState("")
const [refreshtoken, setRefreshToken]=useState("")
React.useEffect(()=>{
localStorage.setItem('user', JSON.stringify(user));
}, []);
React.useEffect(()=>{
const data = localStorage.getItem('user');
if(data){
setUser(JSON.parse(data));
}
}, []);
return(
<BrowserRouter>
<InfoContext.Provider value={{replies, setReplies, artists, setArtists, messages, setMessages, songs, setSongs,posts, setPosts, user, setUser, accesstoken, setAccesToken, refreshtoken, setRefreshToken}}>
<Route exact path="/signup/:id/:access_token" render={()=><Signup />} />
<Route exact path="/" render={()=><Login />} />
<Route exact path="/home/:id/:access_token/:refresh_token" render = {()=> <Homepage ></Homepage>} />
<Route exact path="/artist/:artistid" render = {()=> <ArtistPage ></ArtistPage>} />
<Route exact path="/map" render={()=><MapLeaflet />} />
</InfoContext.Provider>
</BrowserRouter>
);
}
export default App;