1.withRouter作用:把不是通过路由切换过来的组件中,将react-router 的 history、location、match 三个对象传入props对象上
 
默认情况下必须是经过路由匹配渲染的组件才存在this.props,才拥有路由参数,才能使用编程式导航的写法,执行this.props.history.push('/detail')跳转到对应路由的页面
然而不是所有组件都直接与路由相连(通过路由跳转到此组件)的,当这些组件需要路由参数时,使用withRouter就可以给此组件传入路由参数,此时就可以使用this.props
 
2.Redirect渲染<Redirect>将导航到新位置。新位置将覆盖历史堆栈中的当前位置
- to: object

要重定向到的位置。

`
<Redirect to={{
pathname: '/login',
search: '?utm=your+face',
state: { referrer: currentLocation }
}}/> - push: bool 当为true时,重定向会将新条目推入历史记录,而不是替换当前条目。 ` <Redirect push to="/somewhere/else"/> - from: string 要重定向的路径名。这只能用于在<Switch>内部呈现<Redirect>时匹配位置。
有关详细信息,请参阅<Switch children>。https://reacttraining.com/web/api/Switch/children-node ` <Switch>
<Redirect from='/old-path' to='/new-path'/>
<Route path='/new-path' component={Place}/>
</Switch>
import React, { Component } from "react";
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter
} from "react-router-dom"; ////////////////////////////////////////////////////////////
// 1. Click the public page
// 2. Click the protected page
// 3. Log in
// 4. Click the back button, note the URL each time function AuthExample() {
return (
<Router>
<div>
<AuthButton />
<ul>
<li>
<Link to="/public">Public Page</Link>
</li>
<li>
<Link to="/protected">Protected Page</Link>
</li>
</ul>
<Route path="/public" component={Public} />
<Route path="/login" component={Login} />
<PrivateRoute path="/protected" component={Protected} />
</div>
</Router>
);
} /*登录控制*/
const fakeAuth = {
isAuthenticated: false,
authenticate(cb) {//登录授权
this.isAuthenticated = true;
setTimeout(cb, 100); // fake async
},
signout(cb) {//退出登录
this.isAuthenticated = false;
setTimeout(cb, 100);
}
}; /*登录成功组件*/
const AuthButton = withRouter(
/*withRouter作用:把不是通过路由切换过来的组件中,将react-router 的 history、location、match 三个对象传入props对象上*/
({ history,location,match }) =>{
// console.log(history);
// console.log(location);
// console.log(match); return fakeAuth.isAuthenticated ? (//已登录认证就显示下面的组件
<p>
Welcome!{" "}
<button
onClick={() => {//退出按钮
fakeAuth.signout(() => history.push("/"));
}}
>
Sign out
</button>
</p>
) : (//没有登录显示下面的组件
<p>You are not logged in.</p>
)
}
); /*重定向路由组件,返回的是一个Route路由*/
function PrivateRoute({ component: Component, ...rest }) {
return (
<Route
{...rest}
render={props =>
fakeAuth.isAuthenticated ? (
<Component {...props} />
) : (//没有登录就显示下面的路由匹配到登录组件
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);
} /*公共页面无需登录就能访问*/
function Public() {
return <h3>Public</h3>;
} /*登录之后访问的组件*/
function Protected() {
return <h3>Protected</h3>;
} /*登录组件*/
class Login extends Component {
state = { redirectToReferrer: false };//重定向状态 login = () => {//登录方法
fakeAuth.authenticate(() => {
this.setState({ redirectToReferrer: true });//登录进行重定向
});
}; render() {
let { from } = this.props.location.state || { from: { pathname: "/" } };
let { redirectToReferrer } = this.state;
console.log(from);//Object {pathname: "/protected", search: "", hash: "", state: undefined, key: "0hr10n"}
if (redirectToReferrer) return <Redirect to={from} />;//登录之后重定向到来时的这个组件 return (//如果没有登录就显示这个登录组件
<div>
<p>You must log in to view the page at {from.pathname}</p>
<button onClick={this.login}>Log in</button>
</div>
);
}
} export default AuthExample;

转载自https://reacttraining.com/react-router/web/example/auth-workflow

https://edu.51cto.com/lecturer/11857712.html 星星课堂web前端系列课程
https://edu.51cto.com/course/23133.html js进阶与组件化实战课程
https://edu.51cto.com/course/26063.html vue零基础入门课程
https://edu.51cto.com/course/22393.html xhtml与css基础入门课程

React-Router示例(重定向与withRouter)的更多相关文章

  1. [转] React Router 使用教程

    PS:react-route就是一个决定生成什么父子关系的组件,一般和layout结合起来,保证layout不行,内部的子html进行跳转 你会发现,它不是一个库,也不是一个框架,而是一个庞大的体系. ...

  2. React Router 4.x 开发,这些雷区我们都帮你踩过了

    前言 在前端框架层出不穷的今天,React 以其虚拟 DOM .组件化开发思想等特性迅速占据了主流位置,成为前端开发工程师热衷的 Javascript 库.作为 React 体系中的重要组成部分:Re ...

  3. React Router教程

    React Router教程 React项目的可用的路由库是React-Router,当然这也是官方支持的.它也分为: react-router 核心组件 react-router-dom 应用于浏览 ...

  4. React Router API文档

    React Router API文档 一.<BrowserRouter> 使用HTML5历史记录API(pushState,replaceState和popstate事件)的<Rou ...

  5. React Router学习

    React Router教程 本教程引用马伦老师的的教程 React项目的可用的路由库是React-Router,当然这也是官方支持的.它也分为: react-router 核心组件 react-ro ...

  6. React躬行记(13)——React Router

    在网络工程中,路由能保证信息从源地址传输到正确地目的地址,避免在互联网中迷失方向.而前端应用中的路由,其功能与之类似,也是保证信息的准确性,只不过来源变成URL,目的地变成HTML页面. 在传统的前端 ...

  7. React Router 使用教程

    一.基本用法 React Router 安装命令如下. $ npm install -S react-router 使用时,路由器Router就是React的一个组件. import { Router ...

  8. React Router 用法

    React Router 用法 一.DEMO import React from "react"; import { HashRouter as Router, Route, Li ...

  9. react router @4 和 vue路由 详解(全)

    react router @4 和 vue路由 本文大纲: 1.vue路由基础和使用 2.react-router @4用法 3.什么是包容性路由?什么是排他性路由? 4.react路由有两个重要的属 ...

随机推荐

  1. truncate表时报“唯一/主键被启用的外部关键字引用”解决办法

    前言:清空表时提示"唯一/主键被启用的外部关键字引用"这一警告信息 原因:是因为主键被子表引用,所以对主键进行更改就好了 解决: 使用 alter table table_name ...

  2. 电商管理后台 API 接口文档

    1. 电商管理后台 API 接口文档 1.1. API V1 接口说明 接口基准地址:http://127.0.0.1:8888/api/private/v1/ 服务端已开启 CORS 跨域支持 AP ...

  3. 【LeetCode】300.最长递增子序列——暴力递归(O(n^3)),动态规划(O(n^2)),动态规划+二分法(O(nlogn))

    算法新手,刷力扣遇到这题,搞了半天终于搞懂了,来这记录一下,欢迎大家交流指点. 题目描述: 给你一个整数数组 nums ,找到其中最长严格递增子序列的长度. 子序列是由数组派生而来的序列,删除(或不删 ...

  4. springcloud组件之注册中心eureka学习

    eureka的高可用 微服务架构中最核心的部分是服务治理,服务治理最基础的组件是注册中心.随着微服务架构的发展,出现了很多微服务架构的解决方案,其中包括我们熟知的Dubbo和Spring Cloud. ...

  5. mysql面试题及答案,mysql最新面试题,mysql面试题大全汇总

    mysql最新面试题及答案汇总 Mysql 的存储引擎,myisam和innodb的区别.mysql最新面试题 答: 1.MyISAM 是非事务的存储引擎,适合用于频繁查询的应用.表锁,不会出现死锁, ...

  6. 记一次 .NET 某电商定向爬虫 内存碎片化分析

    一:背景 1. 讲故事 上个月有位朋友wx找到我,说他的程序存在内存泄漏问题,寻求如何解决? 如下图所示: 从截图中可以看出,这位朋友对 windbg 的操作还是有些熟悉的,可能缺乏一定的实操经验,所 ...

  7. 题解 [SBCOI2020] 一直在你身旁

    题目传送门 题目大意 给出一个长度为 \(n\) 的单调不减的序列,每次可以选出一个点,产生贡献 \(a_k\),我们可以得知我们需要找到的数是否大于 \(k\).问找到要找到的数最小花费. \(n\ ...

  8. Win10开启剪贴板

    点击任务栏下方右侧的会话窗口 点击所有设置 在搜索栏中输入剪贴板,点击进入剪贴板设置 开启剪贴板历史记录 按下组合键win + v即可呼出剪贴板

  9. 一个简单的单例模式Demo

    /** * @author :nx014924 * @date :Created in 5/30/2021 1:09 PM * @description: * @modified By: * @ver ...

  10. Golang通脉之函数

    函数是组织好的.可重复使用的.用于执行指定任务的代码块. Go语言中支持函数.匿名函数和闭包,并且函数在Go语言中属于"一等公民". 函数定义 Go语言中定义函数使用func关键字 ...