仅在localStorage w / Redux中保存特定的状态

时间:2017-11-08 16:04:35

标签: javascript object redux local-storage

如何使用Redux在localStorage中保存,只有特定的状态?

例如,我在 list reducer中的状态定义如下:

state = {
    companies: [],
    currentDisplay: '',
    recordNotFound: false,
  }

这是我的combineReducer文件:

const rootReducer = combineReducers({
  list: listReducer,
  form: formReducer
})

localStorage.js:

export const loadState = () => {
  try {
    const serializedState = localStorage.getItem('state')
    if (serializedState === null) {
      return undefined;
    }
    return JSON.parse(serializedState)
  } catch (err) {
    return undefined
  }
}

export const saveState = (state) => {
  try {
    const serializedState = JSON.stringify(state)
    localStorage.setItem('state', serializedState)
  } catch (err) {
    // to define
  }
}

浏览器重新加载后,我只想预加载companies: [{obj1}, {obj2}, ...]数组,其余状态重置为默认值f.e. currentDisplay: ''要平等''。

现在负责此操作的代码如下所示:

store.subscribe(() => {
  saveState({
    list: store.getState().list
  })
})

它显然存储整个列表...... 我想我可以使用setState()轻松地在React中重置这些参数,但是我们想要正确地执行此操作。

1 个答案:

答案 0 :(得分:0)

如果您不需要加载其他参数,则可以仅在companies上保存localStorage参数。

store.subscribe(() => {
  saveState({
    companies: store.getState().list.companies
  })
})