localStorage 获取未定义状态

问题描述

TL;DR: 状态更新正确(从 Redux DevTools 查看),但不会在 Local Storage 中持续存在,因为它表示状态“未定义”(附上截图)。 >

说明: 你好!我是 Redux 的新手。我正在尝试将我的状态保存到本地存储。当我从 Redux DevTools 和 console.log() 语句查看时,我的状态正在正确更新。但是,当我检查应用程序的本地存储时,它显示状态未定义。

我想做什么: 每当我按下其中一个组件中的“添加”按钮(然后我想将其保存到浏览器的 Local Storage)时,我都会向我的购物车添加一项服务。

以下是 Redux DevTools 和浏览器本地存储的截图:

enter image description here

enter image description here

请帮我查找并解决问题。

这是我的根组件 App.js代码,其中包含我的 Redux StorelocalStorage funtions

import Servicesdata from "./ServicesData";
import { createStore } from "redux";
import reducer from "./Reducer";
import { Provider } from "react-redux";

// Local Storage Functions:
function savetoLocalStorage(state) {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem("state",serializedState);
  } catch (e) {
    console.log(e);
  }
}

function loadFromLocalStorage() {
  try {
    const serializedState = localStorage.getItem("state");
    if (serializedState === null) return undefined;
    return JSON.parse(serializedState);
  } catch (e) {
    console.log(e);
    return undefined;
  }
}

//initial store
const initialStore = {
  services: Servicesdata,cart: [],bill: 0,// quantity: 0,total_items: 0,//saves total items in the cart
};

const persistedState = loadFromLocalStorage();

//store
const store = createStore(
  reducer,persistedState,window.__Redux_DEVTOOLS_EXTENSION__ && window.__Redux_DEVTOOLS_EXTENSION__()
);

store.subscribe(() => savetoLocalStorage(store.getState));

const App = () => {
  return (
    <Provider store={store}>
        //more code
    </Provider>
  );
};

export default App;

在我的 Reducer.js 中,我只是发送一个 INCREASE 操作以将新商品添加到购物车。

解决方法

将 store.getState 改为 store.getState()