我有一个需要进行身份验证的应用程序 我制作了react-router身份验证工作流程的精确副本(https://reacttraining.com/react-router/web/example/auth-workflow)
Auth.js
const auth = {
isAuthenticated: false,
authenticate(data, scb, fcb) {
fetch("/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(res => {
console.log(res);
localStorage.setItem("token", res.token);
this.isAuthenticated = true;
scb();
})
.catch(ex => {
this.isAuthenticated = false;
fcb();
});
},
signout(cb) {
localStorage.removeItem("token");
this.isAuthenticated = false;
cb();
},
checkSignIn(cb, fcb) {
fetch("api/user/me", {
headers: {
"content-type": "application/json",
"x-auth-token": localStorage.token
}
})
.then(res => res.json())
.then(res => {
console.log("here");
this.isAuthenticated = true;
cb();
})
.catch(err => {
console.log("here in checksign in catch");
this.isAuthenticated = false;
fcb();
});
}
};
export default auth;
现在,当页面加载时,我使用checkSignIn方法并将用户通过身份验证而将用户重定向到仪表板
主要问题是,如果令牌到期,我的API调用将被拒绝,现在我想将用户重定向回Login,我使用signout方法并传递回调以更改组件的状态并返回,但是问题是我在代码中看到太多重复,在每个api调用中,如果api调用失败或者我必须使用withRouter(HOC),我必须传递一个回调以更改页面状态,但是我必须包装每个组件中。 有没有其他方法可以实现此功能