React / Redux在哪里设置sessionStorage

时间:2018-01-10 01:10:06

标签: reactjs react-redux fetch-api session-storage

我正在处理我的第一个react / redux应用程序,我不知道应该在哪里调用sessionStorage.setItem()。我目前正在从loginUserSuccess()操作中存储用户凭据,但我不确定这是我应该这样做的地方。此外,我使用fetch来发出请求,并希望将用户的authToken添加到所有请求中。我正在研究fetch-intercept,但没有提供太多文档来修改标题。

动作/ loginActions.js

export function loginUser(user) {
  return function(dispatch) {
    return LoginApi.login(user).then(creds => {
      dispatch(loginUserSuccess(creds));
    }).catch(error => {
      throw(error);
    });
  };
}

export function loginUserSuccess(creds) {
  sessionStorage.setItem('credentials', JSON.stringify(creds));
  return {
    type: types.LOGIN_USER_SUCCESS,
    state: creds
  }
}

API / packageApi.js

class PackageApi {
  // called on successful login
  static getAllPackages() {
    const request = new Request('/my/endpoint', {
      method: 'GET',
      headers: new Headers({
        'AUTHORIZATION': `Bearer ${JSON.parse(sessionStorage.credentials).authToken}`
      })
    });
    return fetch(request).then(response => {
      return response.json();
    }).catch(error => {
      return error;
    });
  }
}

export default PackageApi;

2 个答案:

答案 0 :(得分:2)

考虑到Dan Abramov的解释,我们有以下几点:

store / sessionStorage.js

export const loadState = () => {
  try {
    const serializedState = sessionStorage.getItem('state');

    if (serializedState === null) {
      return undefined;
    }

    return JSON.parse(serializedState);
  } catch (error) {
    return undefined;
  }
};

export const saveState = (state) => {
  try {
    const serializedState = JSON.stringify(state);
    sessionStorage.setItem('state', serializedState);
  } catch (error) {
    // Ignore write errors.
  }
};

store / index.js

import { createStore } from 'redux';
import rootReducer from '../reducers';
import { loadState, saveState } from './sessionStorage';

const persistedState = loadState();
const store = createStore(rootReducer, persistedState);

store.subscribe(() => {
  saveState(store.getState());
});

完整说明:https://egghead.io/lessons/javascript-redux-persisting-the-state-to-the-local-storage

答案 1 :(得分:1)

sessionStorage视为另外一家商店。这个商店需要与Redux同步,以便它正常工作。我认为减速机是正确的地方。这是您进行数据更改和数据初始化的地方。