[React Router v4] Redirect to Another Page

本文介绍如何使用React Router v4实现优雅的页面重定向,避免浏览器历史记录问题及无限重定向。通过路径匹配和Redirect组件,实现不同URL路径下的重定向逻辑。

Overriding a browser's current location without breaking the back button or causing an infinite redirect can be tricky sometimes. In this lesson we'll learn how React Router v4 allows us to easily achieve a redirect without getting bogged down in browser history.

 

import React from 'react';
import { Link, Route, Redirect } from 'react-router-dom';

const Menu = () => (
    <div>
        <h1>Menu</h1>
        <Link to="/menu/food">Food</Link>
        <Link to="/menu/drinks">Drinks</Link>
        <Link to="/menu/123">Redirect</Link>

        <Route path="/menu/:section([a-z]+)" render={({ match }) => {
            return <h3>Section: {match.params.section}</h3>
        }}>
        </Route>
        <Route path="/menu/:section(\d+)" render={({ match }) => {
            return <Redirect to="/menu/food"></Redirect>
        }}></Route>
    </div>
);

export default Menu;

 

So if we hit /menu/food or /menu/drink, we will go to:

        <Route path="/menu/:section([a-z]+)" render={({ match }) => {
            return <h3>Section: {match.params.section}</h3>
        }}>

Becase :section([a-z]+) match 'food' or 'drink'.

 

If we hit /menu/123, we will go to:

        <Route path="/menu/:section(\d+)" render={({ match }) => {
            return <Redirect to="/menu/food"></Redirect>
        }}></Route>

It will render Redirect component, and redirect us to /menu/food 

 

转载于:https://www.cnblogs.com/Answer1215/p/6603163.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值