本地主机存储

Localhost storage

所以下面的代码是我试图让 localStorage 在页面刷新后保持用户状态的方式。

这基本上适用于主页,每当我刷新时,我都会看到 localStorage 确实持续存在,即使刷新也是如此。但是,当我通过与网页交互并在该页面上刷新时在某个地方溃败时,我丢失了 localStorage

我正在通过 react useContext 函数传递用户状态(其 setter 是 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;




问题是我在将用户设置为本地存储中的用户对象之前没有检查用户是否存在!您还需要在 useEffect 应该 运行.

的括号中添加用户