我正在尝试将我的redux持久化到localStorage,但我不知道如何将它添加到redux-工具箱的configureStore函数中。
错误:
类型'{ reducer:{ progress: Reducer;};persistedState: any;}‘的persistedState参数不能分配给'ConfigureStoreOptions<{位移量: number;},AnyAction>’的参数。对象文字只能指定已知的属性,并且'persistedState‘在'ConfigureStoreOptions<{ AnyAction: number;},AnyAction>’类型中不存在。
代码:
localStorage.ts
export const loadState = () => {
try {
const serializedState = localStorage.getItem("state");
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
};index.tsx
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import counterSlice from "./store/reducers/counterSlice";
import { configureStore } from "@reduxjs/toolkit";
// import throttle from "lodash.throttle";
import { Provider } from "react-redux";
import { loadState, saveState } from "./store/localStorage";
const reducer = {
progress: counterSlice
};
const persistedState = loadState();
const store = configureStore({
reducer,
persistedState
});
store.subscribe(() => {
saveState({
progress: store.getState().progress
});
});
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);发布于 2020-01-17 18:01:25
我是Redux工具包的创建者。persistedState不是configureStore的有效配置选项。The correct field name is preloadedState。
发布于 2020-01-17 10:42:26
不要使用configureStore,而是使用createStore。对我来说,这是可行的:
const store = createStore(
reducer,
persistedState
);完整的例子:
const loadFromLocalStorage = () => {
try {
const serializedState = localStorage.getItem('state');
return JSON.parse(serializedState);
} catch (e) {
throw new Error(e)
}
};
const saveToLocalStorage = state => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
} catch (e) {
throw new Error(e)
}
};
const state= loadFromLocalStorage();
const store = createStore(
reducer,
state
);
store.subscribe(() => {
saveToLocalStorage(store.getState());
});https://stackoverflow.com/questions/59785287
复制相似问题