你好,当我从另一个组件调用 Auth.isAuthenticated() 时,我有这个类,它总是返回 false(它的默认值),即使服务器返回 200 响应,女巫设置 this.authenticated = true 。 我如何使用 promises 让方法等到 fetch 调用完成然后返回结果
编辑: 我需要返回 bool 值 true 或 false,因此基于此,我可以显示或隐藏组件,所有答案都有帮助,但我需要一个 bool 值而不是 promise 任何帮助请
class Auth {
constructor() {
this.authenticated = false;
}
isAuthenticated() {
//get token from local storage if there is one
const jwttoken = localStorage.getItem('jwttoken');
const bearer = 'Bearer ' + jwttoken;
const data = new FormData();
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`${REACT_APP_URL}/api/auth/verify`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': bearer,
},
body: data
}).then(
(response) => {
response.json()
.then((res) => {
if (response.status === 200) {
this.authenticated = true;
}
if (response.status === 401) {
localStorage.removeItem('jwttoken');
this.authenticated = false;
}
})
}
).catch((err) => {
// console.log(err)
});
return this.authenticated;
}
}
export default new Auth();
我从另一个组件调用 Auth.isAuthenticated() === true
export const PrivateRoute = ({ component: Component, ...rest }) => {
return (
<Route {...rest} render={(props) => (
Auth.isAuthenticated() === true
? <Component {...props} />
: <Redirect to='/admin' />
)} />
)
}
最佳答案
假设您要编写一个函数,该函数返回一个 promise 并在某些操作完成时解析(例如 API 调用)。你可以这样写:
const myAsyncFunction = () =>{
return new Promise((resolve, reject) =>{
//Faking an API Call
setTimeout(() => resolve('data'), 400)
})
}
给你!现在你有一个函数返回一个将在 400 毫秒内解决的 promise 。现在您需要使用 .then()
方法或 async await
语句。
const sideEffects = async () =>{
const result = await myAsyncFunction()
console.log(result) //'data'
}
关于javascript - React 类如何在 promise 获取调用后返回 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55405187/