1

即使重新加载页面,我也想保存状态更改。我已经在 console.log 中检查了我的 oldState 常量,它可以工作。但是我的用户界面没有显示本地存储的状态。如何在 preloadedState 中使用我的 oldState 常量?

const saveState = state => {
  try {
    const serialisedState = JSON.stringify(state)
    window.localStorage.setItem('appState', serialisedState)
  } catch (err) {
    // error message
  }
}

const loadState = () => {
  try {
    const serialisedState = window.localStorage.getItem('appState')
    console.log(serialisedState)
    if (!serialisedState) return undefined
  } catch (err) {
    // error message
    return undefined
  }
}

const oldState = loadState()

export const store = configureStore({
  reducer: {
    products,
    filters,
    product,
    cart,
  },
  preloadedState: oldState,
})

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

0 回答 0