基于其他答案(以及Jam Creencia 的 Medium 文章)中提供的出色建议和简短代码摘录,这是一个完整的解决方案!
我们需要一个包含 2 个函数的文件,用于将状态保存到本地存储或从本地存储加载状态:
// FILE: src/common/localStorage/localStorage.js
// Pass in Redux store's state to save it to the user's browser local storage
export const saveState = (state) =>
{
try
{
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
}
catch
{
// We'll just ignore write errors
}
};
// Loads the state and returns an object that can be provided as the
// preloadedState parameter of store.js's call to configureStore
export const loadState = () =>
{
try
{
const serializedState = localStorage.getItem('state');
if (serializedState === null)
{
return undefined;
}
return JSON.parse(serializedState);
}
catch (error)
{
return undefined;
}
};
运行代码片段Hide results
展开片段
这些函数由store.js导入,我们在其中配置商店:
注意:您需要添加一个依赖项:npm install lodash.throttle
// FILE: src/app/redux/store.js
import { configureStore, applyMiddleware } from '@reduxjs/toolkit'
import throttle from 'lodash.throttle';
import rootReducer from "./rootReducer";
import middleware from './middleware';
import { saveState, loadState } from 'common/localStorage/localStorage';
// By providing a preloaded state (loaded from local storage), we can persist
// the state across the user's visits to the web app.
//
// READ: https://redux.js.org/recipes/configuring-your-store
const store = configureStore({
reducer: rootReducer,
middleware: middleware,
enhancer: applyMiddleware(...middleware),
preloadedState: loadState()
})
// We'll subscribe to state changes, saving the store's state to the browser's
// local storage. We'll throttle this to prevent excessive work.
store.subscribe(
throttle( () => saveState(store.getState()), 1000)
);
export default store;
运行代码片段Hide results
展开片段
该商店被导入到index.js中,因此可以将其传递到包装****App.js的Provider中:
// FILE: src/index.js
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import App from './app/core/App'
import store from './app/redux/store';
// Provider makes the Redux store available to any nested components
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
运行代码片段Hide results
展开片段
请注意,绝对导入需要对YourProjectFolder/jsconfig.json进行此更改- 这告诉它在第一次找不到文件时在哪里查找文件。否则,您会看到有关尝试从src外部导入某些内容的抱怨。
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
运行代码片段Hide results
展开片段