【发布时间】:2019-08-19 16:07:42
【问题描述】:
你好我有这个类,当我从另一个组件调用 Auth.isAuthenticated() 时,它总是返回 false(它的默认值),即使服务器返回 200 响应,女巫设置 this.authenticated = true 。 如何使用 promise 让方法等到 fetch 调用完成然后返回结果
编辑: 我需要返回布尔值真或假,因此基于此,我可以显示或隐藏组件,所有答案都有帮助,但我需要布尔值而不是承诺任何帮助
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' />
)} />
)
}
【问题讨论】:
标签: javascript reactjs es6-promise