Authenticate async with react-router-v4

前端 未结 3 1450
醉酒成梦
醉酒成梦 2020-12-15 08:29

I have this PrivateRoute component (from the docs):

const PrivateRoute = ({ component: Component, ...rest }) => (
  

        
3条回答
  •  渐次进展
    2020-12-15 08:46

    If you aren't using Redux or any other kind of state management pattern you can use the Redirect component and components state to determine if the page should render. This would include setting state to a loading state, making the async call, after the request has completed save the user, or lack of user to state and render the Redirect component, if criteria is not met the component will redirect.

    class PrivateRoute extends React.Component {
      state = {
        loading: true,
        isAuthenticated: false,
      }
      componentDidMount() {
        asyncCall().then((isAuthenticated) => {
          this.setState({
            loading: false,
            isAuthenticated,
          });
        });
      }
      render() {
        const { component: Component, ...rest } = this.props;
        if (this.state.loading) {
          return 
    LOADING
    ; } else { return ( (
    {!this.state.isAuthenticated && }
    )} /> ) } } }

提交回复
热议问题