React router history.push 回退到 404 路由 [英] React router history.push falls back to 404 route

查看:21
本文介绍了React router history.push 回退到 404 路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Everytime I execute history.push("/path") the url changes to the correct path but the 404 PageNotFound component gets renderered.

// 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:

And I call the history.push after the user requested a password reset:

// 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/loginPageNotFound 组件被渲染.

Everytime the url changes to localhost:3000/login but the PageNotFound component gets rendered.

推荐答案

使用 react-router v5.2.0 和 history v4.9.0 来完成这项工作.

Use react-router v5.2.0 and history v4.9.0 to make this work.

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

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

Try using BrowserHistory https://reactrouter.com/web/example/basic

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

seems there is some issue with customHistory when we use different version

这篇关于React router history.push 回退到 404 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆