React -用户登录和令牌验证



我有一个这样的AuthService组件

class AuthService {
// ... some code here
private static isTokenValid = async (token: string | null) => {
return await axios.post('https://example.net/wp-json/jwt-auth/v1/token/validate', null, {
headers: {
'Authorization': `Bearer ${token}`
}
}).then(res => {
if (res.data.status === 200) return true;
}).catch(e => {
if (e.response.status === 403) return false;
});
}
public static async isAuthorized() {
const token = localStorage.getItem('token');
let isValid;
if (token) isValid = await this.isTokenValid(token);
return token && isValid ? true : false;
}
}

当我尝试在React组件中使用它时,我得到了isAuthorized承诺而不是布尔(真/假)

import AuthService from '../../services/auth/AuthService';
import React, { useEffect, useState } from 'react';
const NavBar = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
useEffect(() => {
const isAuthorized = AuthService.isAuthorized();
if (isAuthorized) setIsLoggedIn(isAuthorized);
}, []);
return (
//...something...
)
}

我哪里做错了?

async函数总是返回一个promise。看到这个。

试试这个useEffect:

useEffect(() => {
AuthService
.isAuthorized()
.then((isAuthorized) => setIsLoggedIn(isAuthorized))
.catch(() => setIsLoggedIn(false));
}, []);

最新更新