使用react-router-v4验证异步

tom*_*456 11 reactjs react-router react-router-v4

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

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

我想改成isAuthenticatedaysnc请求isAuthenticated().但是,在响应返回之前,页面重定向.

为了澄清,该isAuthenticated功能已经建立.

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

piz*_*r0b 13

如果您不使用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>
          )}
        />
      )
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @J.Pedro 本质上客户端 JS 是不安全的。要将 isAuthenticated 变量更改为 true 需要的不仅仅是打开开发控制台 - 您可能必须筛选已编译、缩小的代码,然后代理一个新的 JS 文件。如果有人有足够的决心这样做,他们将能够看到一些“isAuthenticated”UI,但是后端负责显示所有经过身份验证的数据并验证用户已通过身份验证并允许查看数据。因此,即使有人看到经过身份验证的 UI - 保护敏感数据也取决于后端。 (2认同)

Jos*_*ior 11

如果有人对使用钩子而不是类组件的@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 },
                        }}
                    />
                )
            }
        />
    );
};


Run Code Online (Sandbox Code Playgroud)

使用以下方法调用时效果很好:

<PrivateRoute path="/routeA" component={ComponentA} />
<PrivateRoute path="/routeB" component={ComponentB} />
Run Code Online (Sandbox Code Playgroud)

  • 我相信您可以通过将“[setIsAuthenticated]”作为“useEffect()”中的第二个参数传递来防止不必要的异步调用。 (2认同)

Cra*_*les 5

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

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 } }} />
                )
            )
        }
      />
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

为了完整起见,从我的 App.js 中摘录:

<DashboardLayout>
  <PrivateRoute exact path="/status" component={Status} />
  <PrivateRoute exact path="/account" component={Account} />
</DashboardLayout>
Run Code Online (Sandbox Code Playgroud)