使用API调用的ReactJS受保护路由 [英] ReactJS protected route with API call

查看:20
本文介绍了使用API调用的ReactJS受保护路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试保护我在ReactJS中的路线。 在每个受保护的路由上,我要检查保存在本地存储中的用户是否正确。

下面您可以看到我的路线文件(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(),并将我的函数设置为异步?

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

推荐答案

我遇到了相同的问题,并通过将受保护的路由设置为有状态类来解决该问题。

我使用的内部开关

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

我的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;

这篇关于使用API调用的ReactJS受保护路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆