为什么浏览器后退按钮返回一个带有前一个 URL 的空白页面

IT技术 reactjs react-router navigation react-navigation react-router-dom
2021-05-25 09:27:19

在按下浏览器时,back button为什么会显示一个空白页面而不是我之前访问过的组件?只有 URL 被更改为前一个。
使用 React Router v5

这真的很令人沮丧,我该如何解决这个问题?
注册.js

 render() {
    return (
      <div className='signUp-div'>
        <Header />
        <Router history={history}>
          <div className='form-div'>
            <Redirect to='/signup/mobile' /> // Default page
            <Switch>
              <Route exact path={'/signup/mobile'} component={MobileNum} />
              <Route exact path={'/signup/idnumber'}>
                <IdentNumber setPersonalID={this.props.setUserNumber} />
              </Route>
              <Route exact path={'/signup/password'}>
                <CreatePass
                  setIfSignUp={this.props.setIfSignUp}
                />
              </Route>
            </Switch>
          </div>
        </Router>
      </div>
    );
  }

身份证号码.js

const IdentNumber = ({setPersonalID}) => {

  const handleCheckID = () => {
  history.push('/signup/password');
  }
 
  return (
    <div className='form-div'>
      <button              
        onChange={(event) => onChangeHandler(event)}       
      > Page password</button>
    </div>
  );
};

export default IdentNumber;

我解释对了吗?
谢谢

1个回答

从代码沙箱链接中,我观察到一些可能导致此问题的事情。

将您的导入更新import { Router } from "react-router-dom";import { BrowserRouter as Router } from "react-router-dom";

<BrowserRouter> 使用 HTML5 历史 API(pushState、replaceState 和 popstate 事件)使您的 UI 与 URL 保持同步。

路线将保持不变。您使用的是 react-router-dom v5.2.0,可以useHistory用来获取历史对象。useHistory简化了使组件具有路由感知的过程。

随着我的变化:https : //codesandbox.io/s/suspicious-pine-5uwoq

exact除了默认的“/”之外,我们不需要所有路由的键,当它被包含Switch并放置在末尾时exact匹配/signup/mobile/signup/*相同。Switch 仅呈现一条路线,并且首先匹配的路线

一个示例项目供参考。

如果您想自己处理后退按钮事件,请按照以下示例进行操作。

在函数组件中,我们可以通过监听历史对象来处理后退按钮的按下。

import { useHistory } from 'react-router-dom';

const Test = () => {

  const history = useHistory();
  
  useEffect(() => {
    return () => {
      if (history.action === "POP") {
        
      }
    };
  }, [history])
}

收听历史记录useEffect以了解组件是否已卸载。history.listen让我们聆听历史的变化。

示例

import { useHistory } from 'react-router-dom';

const Test = () => {
  const history = useHistory();

  useEffect(() => {
    return history.listen(location => {
      if (history.action === 'POP') {
        
      }
    })
  }, [])
}

react-router-dom现在有Prompt

import {  Prompt } from "react-router-dom";

    <Prompt
       message={(location, action) => {
         if (action === 'POP') {
           // back button pressed
         }

       return location.pathname.startsWith("/test")
        ? true
        : `Are you sure you want to go to ${location.pathname}?`
     }}
     />