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. c15--二位数组

    // // main.c // day08 #include <stdio.h> int main(int argc, const char * argv[]) { /* int scor ...

  2. 【Codeforces 258D】 Count Good Substrings

    [题目链接] http://codeforces.com/contest/451/problem/D [算法] 合并后的字符串一定是形如"ababa","babab&qu ...

  3. js 获取现在时间一个月(N天)后的日期

    欢迎加入前端交流群交流知识&&获取视频资料:749539640 let today = new Date().getTime() let lastDay = getTimeByDay( ...

  4. ROS单线多拨pppoe

    #设置内网IP地址 / ip add add interface=ether1 address=192.168.0.254/255.255.255.0 #设置共享上网 / ip firewall na ...

  5. python 3.7 replace函数的坑

    使用replace时必须用 str=str.replace(old,new) 如果用 str.replace(old,new)会不起作用. 注意:若str中没有old变量,也不会报错 应用: 练习题 ...

  6. Hadoop MapReduce编程 API入门系列之统计学生成绩版本2(十八)

    不多说,直接上代码. 统计出每个年龄段的 男.女 学生的最高分 这里,为了空格符的差错,直接,我们有时候,像如下这样的来排数据. 代码 package zhouls.bigdata.myMapRedu ...

  7. JS 经验总结

    1.IE中div的高度是content+padding+border之和,其它的是content的高度 2.一个标签里面只有一个属性,class='cls1 cls2' 3.同一页面不能出现相同的id ...

  8. tomcat 启动服务器日志小结

    1.tomcat 启动服务配置: 目前主要有  ①把编译好war或者项目直接扔到webapps 目录下, 启动bin目录下的startup.bat 即可   ②  在conf目录下 修改  serve ...

  9. vue2.x阅读笔记

    v-once 作用: 只赋值一次 注意: 包括子项都是只赋值一次 模板 1.v-text v-html 2.{}语法 3.如果是html的属性,则用v-bind绑定,简写: 注意: 1.可以使用jav ...

  10. nodeJs配置相关以及JSON.parse

    nodeJs配置相关 实际上说应用相关更好吧,我不是很懂. 今天在工作中,被同事解决了一个问题,虽然多花了一些额外时间,但长痛不如短痛嘛 实际上的问题就是npm run target等命令可以,但是n ...