在 ReactJS 中,有没有办法不断检查本地存储中保存的 token 是否已过期?如果它已过期,想删除 token 。
遇到以下问题,但它不是仅在页面重新加载时触发吗?:
window.onbeforeunload = function() {
//remove token
return '';
}
最佳答案
以下假设您使用的是 redux...您可以创建一个中间件,它会在 token 过期时触发一个操作...这将允许您处理下游的 reducer。 redux 方法主要是因为 Redux 是目前与 React 一起使用的最流行的状态管理解决方案。
// export the action type used as a const, so it can be imported for
// the reducer to listen for... The export const/key is more convenient
// then you can use a more namespaced string value to help prevent collisions
export const TOKEN_EXPIRED = 'tokenExpiredMiddleware_TokenExpired';
// redux middleware pattern (store) => (next) => (action) => result;
export default function expiredTokenMiddleware(store) {
// here we only care about a handle to the store for store.dispatch
// start checking every 15 seconds, probably want this configurable
setInterval(checkToken.bind(null, store), 15000);
// return a pass-through for the plugin, so other plugins work
return (next) => (action) => next(action);
}
// export checkToken for testing... etc
// should probably be a separate module
export function checkToken(store) {
var tokenId = ''; // TODO: Identify token
var isExpired = true; // TODO: replace with function to get current state
if (isExpired) {
store.dispatch({
type: TOKEN_EXPIRED,
payload: { tokenId },
});
}
};
然后,当您执行 createStore 时,您可以只添加这个将发出适当操作的中间件,然后您可以在适当的 reducer 中处理它...我对窗口的调整大小/滚动事件做了类似的事情,这样我的大小/位置始终设置。
这是使用 ES6+ 语法,因为你使用的是 React 我认为这是一个合理的假设
关于javascript - ReactJS:如何不断检查本地存储中的 token 是否已过期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40751566/