带有 API 调用的 ReactJS 保护路由

Cra*_*acs 1 javascript routes async-await reactjs react-router-dom

我正在尝试在 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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

我的protectedRoute 文件:

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

export default ProtectedRoute;
Run Code Online (Sandbox Code Playgroud)

还有我的功能isRightUserstatus(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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

Bur*_*vas 5

我遇到了同样的问题,并通过使我的受保护路由成为有状态类来解决它。

我使用的内部开关

<PrivateRoute 
    path="/path"
    component={Discover}
    exact={true}
/>
Run Code Online (Sandbox Code Playgroud)

我的 PrivateRoute 课程如下

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