首页 > 解决方案 > 如何在 React 重定向到 Private Route 之前解决 Promise?

问题描述

用例

我想在async()用户尝试访问私人路线时拨打电话。通常在重定向到私有路由时使用同步方法。

这是我使用过的代码,但不了解如何使用异步方法。

class PrivateRoute extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isAdmin: null
    };
  }

  componentDidMount() {
    console.log("PrivateRoute");
    verifyUser().then(res => {
      this.setState({
        isAdmin: res
      });
    });
  }

  render() {
    const { component: Component, ...rest } = this.props;
    return (
      <Route
        {...rest}
        render={props =>
          this.state.isAdmin === true ? (
            <InnerLayout>
              <Component {...props} />
            </InnerLayout>
          ) : this.state.isAdmin === null ? (
            <div>Loading...</div>
          ) : (
            <Redirect
              to={{ pathname: "/Login", state: { from: this.props.location } }}
            />
          )
        }
      />
    );
  }
}

export default PrivateRoute;

上面代码的问题是 componentDidMount() 调用一次。我已经检查了React 路由和私有路由问题,还检查了Authenticate async with react-router-v4 问题,但两个答案都对我不起作用。

如果我尝试在渲染中解决承诺,则会显示以下错误:

错误 - 编译失败

我怎样才能实现这个用例?

标签: reactjsreact-router

解决方案


您可以使用 withRouter ( https://reacttraining.com/react-router/web/api/withRouter )

class PrivateRoute extends Component {
    constructor(props) {
        super(props);

        this.state = {
            isAdmin: null
        }
    }

    componentDidMount() {
        console.log('PrivateRoute');
        verifyUser().then(res => {
            if(!res){
             this.props.history.push('/Login')
           }else
            this.setState({
                isAdmin: res
            })
        });
    }

    render() {
        const { component: Component, ...rest } = this.props;
       if(this.state.isAdmin === null) return <div>Loading ...</div>
       return <Route {...rest} render={props => <InnerLayout><Component/></InnerLayout>}
    }
}

export default withRouter(PrivateRoute);

推荐阅读