[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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值