如何在Axios响应方面对反应进行身份验证



我想渲染组件,如果 isAuthenticated()方法返回true,则一切正常,直到我从Axios响应中返回true/false,似乎忽略了承诺。我应该如何修改代码,应该使用不同的侵犯?

这是我的isAuthenticate()

 isAuthenticated = () =>{
        const cookie = new Cookie();
        axios.get("/api/check", {
            headers : {
                'Authorization' : 'Bearer ' + cookie.get('access_token')
            }})
            .then(function (response) {
                console.log(response.data.auth"); //returns actuall value
                return response.data.auth; // completely ignored
            })
            .catch(function (response) {
                console.log("Klaida isAuthenticated PrivateRoute");
                return false;
            });
    };

这是我的render()

render() {
        const {component: Component, ...rest} = this.props;
        const renderRoute = props => {
            const to = {
                pathname: '/login',
                state: {from: props.location}
            };
            if (this.isAuthenticated) {
                return (
                    <Component {...props} />
                );
            } else {
                return (
                    <Redirect to={to}/>
                );
            }
        };
        return (
            <Route {...rest} render={renderRoute}/>
        );
    }

编辑因此,我将逻辑从isAuthenticated()移至componentWillMount()方法,并添加了状态元素,以知道何时完成获取:

componentWillMount() {
        const cookie = new Cookie();
        let self =this;
        axios.get("/api/check", {
            headers : {
                'Authorization' : 'Bearer ' + cookie.get('access_token')
            }})
            .then(function (response) {
                self.setState({
                    auth: response.data.auth,
                    res: true
                });
                console.log(self.state.auth)
            })
            .catch(function (response) {
                console.log("Klaida isAuthenticated PrivateRoute");
            });
    }

,我在等待响应时确实有条件地渲染:

if(this.state.res){
             return (
                 <Route {...rest} render={renderRoute}/>
             );
         }else{
             return (
                 'loading..'
             );
         }

,其他一切都是相同的

 isAuthenticated = () =>{
        const cookie = new Cookie();
        axios.get("/api/check", {
            headers : {
                'Authorization' : 'Bearer ' + cookie.get('access_token')
            }})
            .then(function (response) {
                console.log(response.data.auth"); //returns actuall value
                return response.data.auth; // <-- here you're returning this from your callback not from your isAuthenticated method
            })
            .catch(function (response) {
                console.log("Klaida isAuthenticated PrivateRoute");
                return false;
            });
}

if (this.isAuthenticated) // <-- here you're not even calling your method

正确的方法将是在组件中拥有某种状态,并根据您的响应是什么设置状态,然后根据您的状态进行渲染

最新更新