用React-Router-V4身份验证异步



我有此PrivateRoute组件(来自文档):

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    isAuthenticated ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

我想将isAuthenticated更改为AYSNC请求isAuthenticated()。但是,在响应返回页面重定向之前。

要澄清,已经设置了isAuthenticated功能。

在决定显示什么之前,我该如何等待异步电话完成?

如果您不使用Redux或任何其他类型的状态管理模式,则可以使用Redirect组件和组件状态来确定页面是否应呈现。这将包括将状态设置为加载状态,进行异步调用,在请求完成后,保存用户或缺乏用户来陈述和渲染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 <div>LOADING</div>;
    } else {
      return (
        <Route {...rest} render={props => (
          <div>
            {!this.state.isAuthenticated && <Redirect to={{ pathname: '/login', state: { from: this.props.location } }} />}
            <Component {...this.props} />
          </div>
          )}
        />
      )
    }
  }
}

如果任何人对@craigmyles实现的感兴趣,而不是类组件:

export const PrivateRoute = (props) => {
    const [loading, setLoading] = useState(true);
    const [isAuthenticated, setIsAuthenticated] = useState(false);
    const { component: Component, ...rest } = props;
    useEffect(() => {
        const fetchData = async () => {
            const result = await asynCall();
            setIsAuthenticated(result);
            setLoading(false);
        };
        fetchData();
    }, []);
    return (
        <Route
            {...rest}
            render={() =>
                isAuthenticated ? (
                    <Component {...props} />
                ) : loading ? (
                    <div>LOADING...</div>
                ) : (
                    <Redirect
                        to={{
                            pathname: "/login",
                            state: { from: props.location },
                        }}
                    />
                )
            }
        />
    );
};

呼叫时效果很好:

<PrivateRoute path="/routeA" component={ComponentA} />
<PrivateRoute path="/routeB" component={ComponentB} />

@pizza-r0b的解决方案对我来说非常有效。但是,我不得不稍微修改解决方案,以防止加载div多次显示多次(一次在应用程序中定义的每个私有路)通过渲染内部 - 而不是外部 - 路由(类似于React Router的Auth示例),来防止加载div。:

class PrivateRoute extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      loading: true,
      isAuthenticated: false
    }
  }
  componentDidMount() {
    asyncCall().then((isAuthenticated) => {
      this.setState({
        loading: false,
        isAuthenticated
      })
    })
  }
  render() {
    const { component: Component, ...rest } = this.props
    return (
      <Route
        {...rest}
        render={props =>
          this.state.isAuthenticated ? (
            <Component {...props} />
          ) : (
              this.state.loading ? (
                <div>LOADING</div>
              ) : (
                  <Redirect to={{ pathname: '/login', state: { from: this.props.location } }} />
                )
            )
        }
      />
    )
  }
}

我的app.js提取的摘录:

<DashboardLayout>
  <PrivateRoute exact path="/status" component={Status} />
  <PrivateRoute exact path="/account" component={Account} />
</DashboardLayout>

最新更新