reactjs - React 路由器 history.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 和 history v4.9.0 来完成这项工作。
https://codesandbox.io/s/quizzical-dan-z3725
或者
尝试使用 BrowserHistory https://reactrouter.com/web/example/basic
当我们使用不同的版本时,customHistory 似乎存在一些问题
推荐阅读
- python - 输出该特定学生获得的平均百分比分数,精确到小数点后两位
- node.js - SQLite 在 Windows 10 上无法与 Electron 和 Node 一起使用
- opencv - OpenCV 拼接 RGB 和深度(英特尔实感)
- android - 如何将我的应用分发到特定城市?
- reactjs - 使用 redux 与 React 钩子连接
- java - 如何在 jira 中使用 AtlassianWikiRenderer
- java - ANDROID STUDIO / SQLiteLog:(1)“LIMIT”附近:语法错误
- flutter - For 循环中的 If 语句 - (如果为 null,则不添加)
- ios - Swift:在关闭 ViewController2 后从 ViewController1 调用方法
- java - 为什么 JBoss EAP 无法启动?