dom*_*tal 14 javascript reactjs react-router
这是我第一次使用ReactJS而不是我的项目,但我试图将任何不存在的路由重定向到我已经制作的404页面.当输入了不匹配的路由任何URL是我的404页,目前显示为预期除了从URL包含/#/.
例如,此网址将重定向到我的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} />;
}
}
Run Code Online (Sandbox Code Playgroud)
404(NotFound)组件:
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;
Run Code Online (Sandbox Code Playgroud)
当URL与任何路由不匹配且 URL包含时,如何将用户重定向到我的404页面/#/?
对于react-router <4.0
如果要显示错误页面而不更改路径
<Route path='*' exact={true} component={errorcomponent} />
Run Code Online (Sandbox Code Playgroud)
如果要显示错误页面并更改路径
<Route path='/error' component={errorcomponent} />
// use redirect to change the Url
<Redirect from='*' to='/error' />
Run Code Online (Sandbox Code Playgroud)
对于react-router 4
保持路径
<Switch>
<Route exact path="/" component={component} />
<Route component={errorcomponent} />
</Switch>
Run Code Online (Sandbox Code Playgroud)
更改网址.
<Switch>
<Route path="/comp" component={component} />
<Redirect to="/error" />
</Switch>
Run Code Online (Sandbox Code Playgroud)
无论您将路径标记放入交换机,都必须放置重定向标记.
| 归档时间: |
|
| 查看次数: |
1822 次 |
| 最近记录: |