如何在Redux Toolkit中使用预加载状态

tjrkku2a  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(169)

我想保存状态中的更改,即使页面被重新加载。我已经在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())
})
laik7k3q

laik7k3q1#

在您的loadState这一行之后

if (!serialisedState) return undefined

您应该返回值

return serialisedState

更新的loadState

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

希望能有所帮助。

相关问题