React.js身份验证

时间:2018-07-26 18:46:47

标签: reactjs authentication react-redux jwt

我有一个react和redux应用程序,在一定时间后用户会注销。我将jwt令牌存储在本地存储中,并在到期时将其删除。在我的app.js文件中,我执行逻辑以检查其是否在那里以及是否到期,但是该代码仅在刷新应用程序后才运行,我正在尝试寻找一种方法来使其不断运行到期逻辑或更好地运行每当当前路线更改时,它都会更新,而不是刷新。预先感谢。

基本结构:

imports 

expiration logic 

class App extends component {
render() {
   return (
         ...
         )
}
}

1 个答案:

答案 0 :(得分:0)

我想您是在应用程序的入口点设置商店的。那时,当商店处于范围内时,我将向窗口添加事件侦听器以检测路线更改(您也可以使用setInterval() ...),然后使用商店的getState()dispatch()方法。

// entrypoint.js (pseudo-code)

// imports...
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';

import App from './components/App';

// create the store
const store = createStore(...)

// listen for route changes
window.addEventListener('popstate', () => {
  const token = store.getState().jwt;

  // handle the case where the token hasn't been set yet
  if (!token) return;

  // test to see if the token is expired and dispatch something if it has
  if (token.isExpired()) {
    store.dispatch({ type: 'TOKEN_EXPIRED' });
  }
});

render(
  <Provider store={store}><App /></Provider>,
  document.getElementById('<your-apps-attachment-point>'),
);