【问题标题】:Redirecting to 404 component without changing URL in the browser?重定向到 404 组件而不更改浏览器中的 URL?
【发布时间】:2016-10-13 20:29:36
【问题描述】:

我正在制作一个通用的 redux 应用程序,如果用户请求一个不存在的 url,他将被重定向到 404 路由,但我有this problem,如果你点击后退按钮,它不会让你离开返回。

有没有办法在不更改 url 的情况下重定向到 404 路由?

我的路线如下所示:

export default (
    <Route path="/" component={App}>
        <IndexRoute component={MainPage} />
        <Route path="venues/:venueName" component={VenueContainer} />
        <Route path="404" component={NotFound} />
        <Route path="*" component={NotFound} />
    </Route>
);

调用这个 redux 动作来重定向:

import { push } from 'react-router-redux';

export default function redirect404() {
    return (dispatch) => {
        dispatch(push('/404'));
    };
}

我现在拥有的东西可以工作,但我可以看到一些用户体验上的挫败感。

编辑:我认为问题出在带有参数的路线上,例如: &lt;Route path="venues/:venueName" component={VenueContainer} /&gt;。 React-router 看到匹配项并且不会重定向到: &lt;Route path="*" component={NotFound} /&gt;.

我正在从外部 API 请求数据,如果没有,我想在不更改 URL 的情况下显示 404:

import axios from 'axios';
import redirect404 from './utilActions';

export function fetchVenue() {
    return (dispatch) => {
        dispatch({
            type: 'FETCH_VENUE',
            payload: axios.get('http://externalAPI.com'),
        })
        .catch((error) => {
            console.info(error);
            dispatch(redirect404());
        });
    };
}

【问题讨论】:

  • 如果你只删除 404 路由会发生什么? * 应该带头调用你的 NotFound 组件而不更改 URL
  • 这不适用于任何具有类似 &lt;Route path="venues/:venueName" component={VenueContainer} /&gt;987654330@ 参数的路由

标签: javascript reactjs redux react-router


【解决方案1】:

尝试使用replace 而不是push

  • push - 将新位置推送到历史记录,成为当前位置
  • replace - 替换历史中的当前位置。

react-router-redux

import { push } from 'react-router-redux';

export default function redirect404() {
  return (dispatch) => {
    dispatch(replace('/404'));
  };
}

【讨论】:

    【解决方案2】:

    完全删除/404 路由并且不要重定向。现在,每次您无法匹配路线时,您的用户都会被重定向到/404。您的 * 路径可以很好地概括。

    【讨论】:

    • 不幸的是,* 路径没有捕获带有参数的路线:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 2020-06-15
    相关资源
    最近更新 更多