如何使用ReactJS在URL不匹配任何路由以及URL包含/#/时显示404

2024-01-17

这是我第一次使用 ReactJS,也不是我的项目,但是,我试图将任何不存在的路由重定向到我制作的 404 页面。当输入任何与路由不匹配的 URL 时,我的 404 页面当前会按预期显示apart从 URL 包含时开始/#/.

例如,此 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} />;
    }
}

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 与任何路由都不匹配时,如何将用户重定向到我的 404 页面and当 URL 包含/#/?


对于反应路由器

如果您想显示错误页面并且不更改路径

<Route path='*' exact={true} component={errorcomponent} />

如果要显示错误页面并更改路径

<Route path='/error' component={errorcomponent} />
 // use redirect to  change the Url
<Redirect from='*' to='/error' />

对于反应路由器 4

保留路径

<Switch>
    <Route exact path="/" component={component} />
    <Route component={errorcomponent} />
 </Switch>

更改网址。

 <Switch>
    <Route path="/comp" component={component} />
   <Redirect to="/error" />
 </Switch>

无论您在交换机内放置路由标记,都必须放置重定向标记。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用ReactJS在URL不匹配任何路由以及URL包含/#/时显示404 的相关文章

随机推荐