【发布时间】:2018-06-28 22:48:41
【问题描述】:
这是我第一次使用 ReactJS 并且不是我的项目,但是我正在尝试将任何不存在的路由重定向到我制作的 404 页面。当 URL 包含 /#/ 时输入任何与路由不匹配的 URL 除了,我的 404 页面当前正在按预期显示。
比如这个网址会重定向到我的404页面:
http://localhost:8080/non-existent-url
但是这个 URL 只会加载我应用的默认路由(主页):
http://localhost:8080/#/non-existent-url
我不知道/#/ 是做什么用的,看来该应用程序将显示带有或不带它的有效路线的页面。
精简路线文件:
import React from "react";
import { Router, Route, IndexRoute, browserHistory, hashHistory, Redirect } from "react-router/es";
import willTransitionTo from "./routerTransition";
import App from "./App";
import DashboardContainer from "./components/Dashboard/DashboardContainer";
import DashboardAccountsOnly from "./components/Dashboard/DashboardAccountsOnly";
import NotFound from './components/NotFound';
const history = __HASH_HISTORY__ ? hashHistory : browserHistory;
class Auth extends React.Component {
render() {return null; }
}
const routes = (
<Route path="/" component={App} onEnter={willTransitionTo}>
<IndexRoute component={DashboardContainer}/>
<Route path="/auth/:data" component={Auth}/>
<Route path="/dashboard" component={DashboardContainer}/>
<Route path='*' exact={true} component={NotFound} />
</Route>
);
export default class Routes extends React.Component {
render() {
return <Router history={history} routes={routes} />;
}
}
404(未找到)组件:
import React from 'react';
import {Link} from "react-router/es";
import Translate from "react-translate-component";
var image = require("assets/404.png");
const NotFound = () =>
<div className="grid-block main-content wrap regular-padding">
<div className="grid-content small-12" style={{marginTop:"200px"}}>
<div style={{ textAlign:"center"}}>
<img style={{marginBottom:"1.2rem"}} src={image} />
<h3>404 page not found</h3>
<p>This page does not exist.</p>
<Link className="button" to={"/dashboard"}>
<Translate style={{color:"#fff"}} content="account.home" />
</Link>
</div>
</div>
</div>
export default NotFound;
当 URL 不匹配任何路由并且当 URL 包含 /#/ 时,我如何将用户重定向到我的 404 页面?
【问题讨论】:
-
你使用的是哪个版本的 React Router?
-
您可能想阅读 React Router 文档中的
和 之间的区别。 reacttraining.com/react-router/web/api/HashRouter -
看起来你需要做的就是使用
browserHistory而不是hashHistory像const history = browserHistory; -
@MattD 我正在使用 react-router v3.0.2。我尝试了 Shubham 的建议,但没有任何区别。
-
Please check here。它会帮助你。
标签: javascript reactjs react-router