[React Router] Create a ProtectedRoute Component in React Router (setState callback to force update)
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 readingthis.state
right after callingsetState()
a potential pitfall. Instead, usecomponentDidUpdate
or asetState
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 theupdater
argument below. Link
相关文章
- 小前端读源码 - React组件更新原理
- 【译】JavaScript实现文字剪贴板&React版本
- react项目的@路径配置
- React源码学习入门(五)详解React中的Transaction事务机制
- react中配置图片容错
- React魔法堂:echarts-for-react源码略读
- 【Techo Day 腾讯技术开放日】jira React 实战
- react源码分析--深度理解React.Context
- Jest:给你的 React 项目加上单元测试
- 校招前端经典react面试题(附答案)
- react源码分析:深度理解React.Context
- React 项目部署后,页面404解决
- React--15:生命周期新版本
- React markdown发布文章后展示[2]
- react源码分析:深度理解React.Context_2023-02-07
- React源码分析6-hooks源码_2023-02-21
- react 基础之组件篇二——Style in React
- ORA-16444: ALTER SYSTEM FLUSH REDO TO STANDBY failed due to a corrupted control file or online log file. ORACLE 报错 故障修复 远程处理