[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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2017-04-08 [SCSS] Organize SCSS into Multiple Files with Partials
2017-04-08 [CSS Flex] Justify-content
2017-04-08 [CSS Flex] Flex direction
2016-04-08 [Git] Automatically running tests before commits with ghooks