In this lesson we'll create a protected route just for logged in users. We'll combine a Route with a render prop and use a loggedIn prop to determine if the route should be allowed to be accessed. Finally we'll use nav state to preserve the location the user visited and redirect them back to the protected route once they login.

1. Create a ProtectedRoute is nothing but just a react component render a Route component:

  • check the 'loggedIn' props, if true, then using render prop to render the component normally.
  • If 'loggedIn' props is false, then use 'Redirect' component to redirect to Home page. also pass the route state.
const ProtectedRoute = ({ component: Comp, loggedIn, path, ...rest }) => {
return (
<Route
path={path}
{...rest}
render={(props) => {
return loggedIn ? (
<Comp {...props} />
) : (
<Redirect
to={{
pathname: "/",
state: {
prevLocation: path,
error: "You need to login first!",
},
}}
/>
);
}}
/>
);
};

2. When the login button is clicked, we want to force udpate the state using callback in setState:

    this.setState(
{
loggedIn: true,
},
() => {
this.props.history.push(prevLocation || "/");
},
);
};

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below. Link

[React Router] Create a ProtectedRoute Component in React Router (setState callback to force update)的更多相关文章

  1. [React Native] Use the SafeAreaView Component in React Native for iPhone X Compatibility

    In this lesson, you will learn how to use the SafeAreaView component to avoid the sensor cluster (th ...

  2. [React Native] Create a component using ScrollView

    To show a list of unchanging data in React Native you can use the scroll view component. In this les ...

  3. [React Native] Using the Image component and reusable styles

    Let's take a look at the basics of using React Native's Image component, as well as adding some reus ...

  4. [React] Refactor a Class Component with React hooks to a Function

    We have a render prop based class component that allows us to make a GraphQL request with a given qu ...

  5. React.Component 与 React.PureComponent(React之性能优化)

    前言 先说说 shouldComponentUpdate 提起React.PureComponent,我们还要从一个生命周期函数 shouldComponentUpdate 说起,从函数名字我们就能看 ...

  6. [React] Use React.memo with a Function Component to get PureComponent Behavior

    A new Higher Order Component (HOC) was recently released in React v16.6.0 called React.memo. This be ...

  7. React.Component 和 React.PureComponent 、React.memo 的区别

    一 结论 React.Component 是没有做任何渲染优化的,但凡调用this.setState 就会执行render的刷新操作. React.PureComponent 是继承自Componen ...

  8. how to design a search component in react

    how to design a search component in react react 如何使用 React 设计并实现一个搜索组件 实时刷新 节流防抖 扩展性,封装,高内聚,低耦合 响应式 ...

  9. React 源码剖析系列 - 不可思议的 react diff

      简单点的重复利用已有的dom和其他REACT性能快的原理. key的作用和虚拟节点 目前,前端领域中 React 势头正盛,使用者众多却少有能够深入剖析内部实现机制和原理. 本系列文章希望通过剖析 ...

随机推荐

  1. md5 c# unicode 互换(原创)

    php 代码 $input='中国'; $result= md5($input); $temp=iconv("UTF-8", "UTF16LE", $input ...

  2. PHP检测输入数据是否合法常用的类(转)

    <?php class Fun{ function isEmpty($val) { if (!is_string($val)) return false; //是否是字符串类型 if (empt ...

  3. H3C交换机DHCP&nbsp;Server配置的六个方面

    H3C交换机DHCP Server配置的六个方面 在交换机上面配置DHCP内容是司空见惯的了.那么这里我们就讲解一下H3C交换机DHCP Server配置内容.之后的文章中,我们还对针对其他方面的配置 ...

  4. AJAX复习笔记

    AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术.通过在后台与服务器进行少量数据交换,AJAX 可况下更新以使网页实现异步更新. 工作原理: AJAX是基于现有的Internet ...

  5. python-sqlite3事务

    sqlite3事务总结: 在connect()中不传入 isolation_level 事务处理: 使用connection.commit() #!/usr/bin/env python # -*- ...

  6. Codeforces Round #198 (Div. 2)C,D题解

    接着是C,D的题解 C. Tourist Problem Iahub is a big fan of tourists. He wants to become a tourist himself, s ...

  7. 大数字运算——2、BigDecimal

    package com.wh.BigInteger; import java.math.BigDecimal; import java.util.Arrays; /** * @author 王恒 * ...

  8. express搭建一个web服务器

    npm install express -g                           express这个库可以使用了. npm install express-generator -g   ...

  9. javascript中的构造函数和原型及原型链

    纯属个人理解,有错误的地方希望大牛指出,以免误人子弟 1.构造函数: 构造函数的作用 : 初始化由new创建出来的对象    new 的作用: 创建对象(空对象) new 后面跟的是函数调用,使用ne ...

  10. ubuntu+win10双系统,调整分区大小后进入了emergency mode

    问题背景: 装了Ubuntu+win10双系统,在Ubuntu下面挂载了Windows的D盘.后来因为D空间不够,进入Windows压缩C盘分区,扩大了D盘.重启后无法启动Ubuntu,进入了emer ...