[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 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

 

 

posted @   Zhentiw  阅读(265)  评论(0编辑  收藏  举报
编辑推荐:
· 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
点击右上角即可分享
微信分享提示