ReactJS 使用 API 调用保护路由

ReactJS protected route with API call

我试图在 ReactJS 中保护我的路由。 在每个受保护的路由上,我想检查保存在 localStorage 中的用户是否正常。

下面你可以看到我的路线文件(app.js):

class App extends Component {
    render() {
        return (
            <div>
                <Header />
                <Switch>
                    <Route exact path="/" component={Home} />
                    <Route path="/login" component={Login} />
                    <Route path="/signup" component={SignUp} />
                    <Route path="/contact" component={Contact} />
                    <ProtectedRoute exac path="/user" component={Profile} />
                    <ProtectedRoute path="/user/person" component={SignUpPerson} />
                    <Route component={NotFound} />
                </Switch>
                <Footer />
            </div>
        );
    }
}

我的受保护路由文件:

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

export default ProtectedRoute;

还有我的功能isRightUser。当数据对登录的用户无效时,此函数发送 status(401)

async isRightUser() {
    var result = true;
    //get token user saved in localStorage
    const userAuth = this.get();

    if (userAuth) {
        await axios.get('/api/users/user', {
            headers: { Authorization: userAuth }
        }).catch(err => {
            if (!err.response.data.auth) {
                //Clear localStorage
                //this.clear();
            }

            result = false;
        });
    }

    return result;
}

这段代码不起作用,我也不知道为什么。 也许我需要在调用之前用 await 调用我的函数 AuthService.isRightUser() 并将我的函数异步 ?

如何更新我的代码以在访问受保护页面之前检查我的用户?

当您像在 AuthService.isRightUser() 中那样用 async 注释函数时,它 returns 和 Promise 并且您没有相应地处理方法的响应。

正如您所建议的,您可以使用 await 调用方法 AuthService.isRightUser() 并使用 async 注释您传递给 render 属性 的函数.

或者您可以使用 .then().catch() 而不是三元运算符

来处理 AuthService.isRightUser() 的响应

我遇到了同样的问题并通过将我的受保护路由设置为有状态 class.

解决了这个问题

我使用的内部开关

<PrivateRoute 
    path="/path"
    component={Discover}
    exact={true}
/>

而我的 PrivateRoute class 如下

class PrivateRoute extends React.Component {

    constructor(props, context) {
        super(props, context);

        this.state = {
            isLoading: true,
            isLoggedIn: false
        };

        // Your axios call here

        // For success, update state like
        this.setState(() => ({ isLoading: false, isLoggedIn: true }));

        // For fail, update state like
        this.setState(() => ({ isLoading: false, isLoggedIn: false }));

    }

    render() {

        return this.state.isLoading ? null :
            this.state.isLoggedIn ?
            <Route path={this.props.path} component={this.props.component} exact={this.props.exact}/> :
            <Redirect to={{ pathname: '/login', state: { from: this.props.location } }} />

    }

}

export default PrivateRoute;