反应路由器历史记录.push回退到404路由

问题描述

每次执行history.push("/path")时,URL都会更改为正确的路径,但是404 PageNotFound组件会被渲染。

// indes.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import {App} from './App';
import history from "./customHistory";
import {Router} from "react-router";

ReactDOM.render(
    <React.StrictMode>
        <Router history={history}>
           <App/>
        </Router>
    </React.StrictMode>,document.getElementById('root')
);
/// App.tsx
import React,{Component} from "react"
import {Route,Switch} from "react-router-dom";
import {FrontPage} from './components/FrontPage'
import {LoginPage} from "./components/LoginPage";
import {PageNotFound} from "./components/PageNotFound";
import {RequestPasswordResetPage} from "./components/RequestPasswordResetPage";

export class App extends Component {

    render() {
        return (
            <Switch>
                <Route path={"/"} component={FrontPage} exact={true}/>

                <Route path={"/login"} component={LoginPage} exact={true}/>

                <Route path={"/request_password_reset"} component={RequestPasswordResetPage}
                       exact={true}/>

                <Route path={""} component={PageNotFound}/>
            </Switch>
        )
    }
}

我的历史记录对象如下

// customHistory.ts
import { createbrowserHistory } from "history";

export default createbrowserHistory({});

用户请求重设密码后,我调用了history.push:

// RequestPasswordResetPage.tsx
private handleSubmit(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();

        AccountService.requestPasswordReset(this.state.email)
            .then((ans: Response) => {
                if (ans.ok) {
                    console.log("REDIRECT TO HOME");
                    history.push("/login");
                } else {
                    throw Error(ans.statusText);
                }
            });
    }

每次url更改为localhost:3000/login,但PageNotFound组件被渲染。

解决方法

使用react-router v5.2.0和历史记录v4.9.0来完成这项工作。

https://codesandbox.io/s/quizzical-dan-z3725

OR

尝试使用BrowserHistory https://reactrouter.com/web/example/basic

当我们使用不同的版本时,customHistory似乎存在一些问题

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...