即使在反应路由器中刷新后,有什么方法可以坚持在同一页面上吗?

is there any way to stick on the same page even after refreshing in react router?

嗨,我是 React 的新手,在 React 路由器中遇到了问题。实际上我在 react router dom 中使用 useNavigate 进行导航,一切正常但我的问题是假设最初我在第一页然后使用 useNavigate 到达第二页然后从第二页到第三页。现在什么时候刷新页面,一切都从第 1 页开始,但是,我想要的是,如果我在第 3 页,那么刷新必须在第 3 页,有什么办法可以实现它。

例如我正在使用两个页面(我的目标是如果我在刷新时在第二页我必须在第二页)但是对于当前情况浏览器是从第一页开始的

我正在这样写我的第一页

import react from "react";
import "../../../../css/panel/articleverificationpanel/topmostTray.css";
import axios from "axios";
import { useNavigate } from 'react-router-dom'

class MainLoginAreaForPanel extends react.Component {
  goButtonClicked =() => {
    try {
      const userId = document.getElementById("userId").value;
      const password = document.getElementById("password").value;
      const securityKey = document.getElementById("securityKey").value;
      console.log(userId, password, securityKey);
      const data = {
        userId,
        password,
        securityKey,
      };
      axios
        .post(
          `http://localhost:4000/app/panel/articleverification/signin`,
          data
        )
        .then((res) => {
          // means file has been uploaded
          if (res.data.success === 1) {
            console.log(this.props)
            this.props.authorizeUser(true,{})
            this.props.navigation('/panel/articleverification/homepage',{replace:true})
            
          } else {
            throw new Error('Sorry could not verify you');
          }
          
        })
        .catch((error) => {
          alert(error.message);
        });
    } catch (error) {
      alert(error.message);
    }
  }
  render() {
    return (
      <react.Fragment>
        <div id="mainLoginPanelArea">
          <label htmlFor="userId" className="children">
            User id:
          </label>
          {"   "}
          <input type="text" id="userId" name="userId" className="children" />
          <br />
          <br />
          <label htmlFor="password">Password:</label>
          {"   "}
          <input type="text" id="password" name="password" />
          <br />
          <br />
          <label htmlFor="securityKey">Security Key:</label>
          {"   "}
          <input type="text" id="securityKey" name="securityKey" />
          <br />
          <br />
          <br />
          <br />
          <br />
          <br />
          <br />
          <button className="btn" onClick={this.goButtonClicked}>
            GO
          </button>
        </div>
      </react.Fragment>
    );
  }
}

// Wrap and export
export default function(props) {
  const navigation = useNavigate();

  return <MainLoginAreaForPanel {...props} navigation={navigation} />;
}

这就是我写第二页的方式

import react from "react";
import TopmostTrayForPanel from "./topmostTray";
import CardForPanel from "./cardForPanel";
import {Navigate,useNavigate} from 'react-router-dom'
import axios from "axios";

class HomePageForArticalVerificationPanel extends react.Component {
  state = {
    data: [],
  };
  openArticle = (articleId) => {
    this.props.navigation('/panel/articleverification/articlepage',{replace:true,state:
      {articleId:articleId}
    })
  }
  componentDidMount() {
    console.log("loaded");
    this.getUnverifiedArticles();
  }
  
  getUnverifiedArticles() {
    let data = [];
    let cnt = 0;
    let temp = [];
    axios
    .get(
      `http://localhost:4000/app/panel/articleverification/getunverifiedarticles`,
      data
    )
    .then((res) => {
      
      console.log(res)
      if (res.data.success === 1) {
        const articles = res.data.data.articles 
        for (let i = 0; i < articles.length; i++) {
          if (cnt > 2) {
            data.push(<div className="row" key={`extra${i}`}>{temp}</div>);
            cnt = 0;
            temp = [];
          }
          if (cnt <= 2) {
            temp.push(
              <div className="col-sm" key={i}>
                <CardForPanel title={articles[i].title} tags={articles[i].tags} aid={articles[i].aid} openArticle={this.openArticle}></CardForPanel>
              </div>
            );
            cnt++;
          }
          
        }
        if(temp.length !=0){
            data.push(<div className="row" key={`last one`}>{temp}</div>);
        }
        this.setState({
          data: data,
        });
      } else {
        throw new Error('Sorry could not verify you');
      }
      
    })
    .catch((error) => {
      alert(error.message);
    });
    
  }
  render() {
    if (this.props.authorized) {
      return (
      
        <div className="parent_container">
          <TopmostTrayForPanel></TopmostTrayForPanel>
          <div className="container">{this.state.data}</div>
        </div>
      );
    } else {
      return (
        <Navigate to='/panel/articleverification'  />
      )
    }
    
  }
}

// Wrap and export
export default function(props) {
  const navigation = useNavigate();

  return <HomePageForArticalVerificationPanel {...props} navigation={navigation} />;
}

下面是我的路由代码

import React from "react";

import {Routes,Route} from 'react-router-dom'
import EditorPage from './components/editor/classbased/editorPage'
import LoginPageForArticalVerificationPanel from './components/panel/articleverficationpanel/classbased/loginPage'
import HomePageForArticalVerificationPanel from './components/panel/articleverficationpanel/classbased/homePage'
import ArticlePageForArticalVerificationPanel from './components/panel/articleverficationpanel/classbased/articlePage'
class App extends React.Component {
  state = {
    authorised:false,
    extras:{}
  }

  authorizeUser = (authorizeState,extras) => {
    console.log('called 1')
    this.setState({
      authorised:authorizeState,
      extras:extras
    })
  }
  render() {
    return (
      <>
        <Routes>
            <Route path='/editor' element={<EditorPage />} />
            <Route path='/panel/articleverification' element={<LoginPageForArticalVerificationPanel authorizeUser={this.authorizeUser}/>} />
            <Route path='/panel/articleverification/homepage' element={<HomePageForArticalVerificationPanel authorized={this.state.authorised}/>} />
            <Route path='/panel/articleverification/articlepage' element={<ArticlePageForArticalVerificationPanel authorized={this.state.authorised}/>} />

        </Routes>
      </>
    );
  }
}
export default App;

据我所知,在导航到嵌套路由之一并重新加载页面后,应用程序重新加载并且 authorized 状态被重置,子路由组件检查此状态并强制重定向回来。

坚持并初始化 authorized 状态 to/from localStorage。

class App extends React.Component {
  state = {
    // Read initial state from localStorage, provide fallback
    authorized: JSON.parse(localStorage.getItem("authorized")) ?? false,
    extras: {}
  }

  componentDidUpdate(prevProps, prevState) {
    // Persist authorized state changes to localStorage
    if (prevState.authroized !== this.state.authorized) {
      localStorage.setItem("authorized", JSON.stringify(authorized));
    }
  }

  authorizeUser = (authorizeState, extras) => {
    console.log('called 1');
    this.setState({
      authorized: authorizeState,
      extras: extras
    })
  }
  render() {
    return (
      <Routes>
        <Route path='/editor' element={<EditorPage />} />
        <Route
          path='/panel/articleverification'
          element={(
            <LoginPageForArticalVerificationPanel
              authorizeUser={this.authorizeUser}
            />
          )}
        />
        <Route
          path='/panel/articleverification/homepage'
          element={(
            <HomePageForArticalVerificationPanel
              authorized={this.state.authorized}
            />
          )}
        />
        <Route
          path='/panel/articleverification/articlepage'
          element={(
            <ArticlePageForArticalVerificationPanel
              authorized={this.state.authorized}
            />
          )}
        />
      </Routes>
    );
  }
}