在Redux应用程序中哪里写localStorage ?

我想将我的状态树的某些部分持久化到localStorage。在什么地方这样做比较合适?减速还是行动?

130455 次浏览

一句话:中间件。

查看redux-persist。或者自己写。

[更新2016年12月18日]编辑删除提及两个类似的项目现在不活跃或弃用。 < br >

减速器从来不是一个合适的地方这样做,因为减速器应该是纯粹的,没有副作用。

我建议只在订阅者中进行:

store.subscribe(() => {
// persist your state
})

在创建存储之前,读取那些持久化的部分:

const persistedState = // ...
const store = createStore(reducer, persistedState)

如果你使用combineReducers(),你会注意到没有收到状态的还原器将使用默认的state参数值正常“启动”。这非常方便。

建议您取消订阅服务器,这样就不会太快地写入localStorage,否则就会出现性能问题。

最后,您可以创建一个中间件,将其封装为替代方案,但我会从订阅者开始,因为这是一个更简单的解决方案,而且工作做得很好。

为了填补Dan Abramov的答案,你可以像这样使用store.subscribe():

store.subscribe(()=>{
localStorage.setItem('reduxState', JSON.stringify(store.getState()))
})

在创建存储之前,检查localStorage并像这样解析键下的任何JSON:

const persistedState = localStorage.getItem('reduxState')
? JSON.parse(localStorage.getItem('reduxState'))
: {}

然后将这个persistedState常量传递给你的createStore方法,如下所示:

const store = createStore(
reducer,
persistedState,
/* any middleware... */
)

如果任何人对上述解决方案有任何问题,您可以编写自己的解决方案。让我给你看看我做了什么。忽略saga middleware的事情,只关注两个事情localStorageMiddlewarereHydrateStore方法。localStorageMiddleware取出所有redux state并将其放入local storagerehydrateStore取出本地存储中的所有applicationState(如果存在)并将其放入redux store

import {createStore, applyMiddleware} from 'redux'
import createSagaMiddleware from 'redux-saga';
import decoristReducers from '../reducers/decorist_reducer'


import sagas from '../sagas/sagas';


const sagaMiddleware = createSagaMiddleware();


/**
* Add all the state in local storage
* @param getState
* @returns {function(*): function(*=)}
*/
const localStorageMiddleware = ({getState}) => { // <--- FOCUS HERE
return (next) => (action) => {
const result = next(action);
localStorage.setItem('applicationState', JSON.stringify(
getState()
));
return result;
};
};




const reHydrateStore = () => { // <-- FOCUS HERE


if (localStorage.getItem('applicationState') !== null) {
return JSON.parse(localStorage.getItem('applicationState')) // re-hydrate the store


}
}




const store = createStore(
decoristReducers,
reHydrateStore(),// <-- FOCUS HERE
applyMiddleware(
sagaMiddleware,
localStorageMiddleware,// <-- FOCUS HERE
)
)


sagaMiddleware.run(sagas);


export default store;

我无法回答@Gardezi,但基于他的代码的选项可能是:

const rootReducer = combineReducers({
users: authReducer,
});


const localStorageMiddleware = ({ getState }) => {
return next => action => {
const result = next(action);
if ([ ACTIONS.LOGIN ].includes(result.type)) {
localStorage.setItem(appConstants.APP_STATE, JSON.stringify(getState()))
}
return result;
};
};


const reHydrateStore = () => {
const data = localStorage.getItem(appConstants.APP_STATE);
if (data) {
return JSON.parse(data);
}
return undefined;
};


return createStore(
rootReducer,
reHydrateStore(),
applyMiddleware(
thunk,
localStorageMiddleware
)
);

不同之处在于我们只是保存了一些动作,你可以使用debounce函数来保存你状态的最后一次交互

我有点晚了,但是我根据这里的示例实现了一个持久状态。如果你想每X秒更新一次状态,这个方法可以帮助你:

  1. 定义一个包装函数

    let oldTimeStamp = (Date.now()).valueOf()
    const millisecondsBetween = 5000 // Each X milliseconds
    function updateLocalStorage(newState)
    {
    if(((Date.now()).valueOf() - oldTimeStamp) > millisecondsBetween)
    {
    saveStateToLocalStorage(newState)
    oldTimeStamp = (Date.now()).valueOf()
    console.log("Updated!")
    }
    }
    
  2. Call a wrapper function in your subscriber

        store.subscribe((state) =>
    {
    updateLocalStorage(store.getState())
    });
    

In this example, the state is updated at most each 5 seconds, regardless how often an update is triggered.

在其他答案(和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;
}
};

这些函数是由store.js导入的,我们在这里配置了我们的store:

注意:你需要添加一个依赖项: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;

存储被导入到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')
)

请注意,绝对导入需要将此更改为YourProjectFolder / jsconfig.json -这将告诉它在哪里查找文件,如果它一开始找不到它们。否则,您将看到试图从src外部导入某些内容的抱怨。

{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}

如果你不需要复制所有redux store到localStorage,你可以使用特定的store参数:

store.subscribe(()=>{
window.localStorage.setItem('currency', store.getState().lang)
})

并像这样设置初始状态参数值:

const initialState = {
currency: window.localStorage.getItem('lang') ?? 'en',
}

在这种情况下,你不需要将const persistedState传递给const store = createStore()

我正在寻找一个关于如何使用redux-toolkit-persist将状态持久化到本地存储的完整示例,但没有成功,直到我遇到上面的@canProm响应来解决我的问题。 这就是我的工作

//package.json
"reduxjs-toolkit-persist": "^7.0.1",
"lodash": "^4.17.21"


//localstorage.ts
import localStorage from 'reduxjs-toolkit-persist/es/storage';
export const saveState = (state: any) => {
try {
console.log(state);
const serializableState = JSON.stringify(state);
localStorage.setItem('globalState', serializableState);
} catch (err) {
console.log('Redux was not able to persist the state into the localstorage');
}
};




export const loadState = () => {
try {
const serializableState: string | any =
localStorage.getItem('globalState');
return serializableState !== null || serializableState === undefined ? JSON.parse(serializableState) : undefined;
} catch (error) {
return undefined;
}
};






//slices - actions
//reduxjs-toolkit-slices.ts
import { combineReducers, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { UserModel } from '../model/usermodel';
import { GlobalState } from './type';


const deaultState: GlobalState = {
counter: 0,
isLoggedIn: false
};


const stateSlice = createSlice({
name: "state",
initialState: deaultState,
reducers: {
isLoggedIn: (state, action: PayloadAction<boolean>) => {
console.log('isLogged');
console.log(state.isLoggedIn);
console.log(action);
state.isLoggedIn = action.payload;
console.log(state.isLoggedIn);
},
setUserDetails: (state, action: PayloadAction<UserModel>) => {
console.log('setUserDetails');
console.log(state);
console.log(action);
//state.userContext.user = action.payload;
}
}
});


//export actions under slices
export const {
isLoggedIn: isUserLoggedAction,
setUserDetails: setUserDetailActions
} = stateSlice.actions;


//TODO: use the optimal way for combining reducer using const
//combine reducer from all slice
export const combineReducer = combineReducers({
stateReducer: stateSlice.reducer
});


//storeConfig
//reduxjs-toolkit-store.ts
import { configureStore } from '@reduxjs/toolkit';
import { throttle } from 'lodash';
import { persistReducer } from 'reduxjs-toolkit-persist';
import autoMergeLevel2 from 'reduxjs-toolkit-persist/lib/stateReconciler/autoMergeLevel2';
import storage from 'reduxjs-toolkit-persist/lib/storage';
import { loadState, saveState } from './localStorage';
import { combineReducer } from './reduxjs-toolkit-slices';


// persist config
const persistConfig = {
key: 'root',
storage: storage,
stateReconciler: autoMergeLevel2,
};
const persistedReducer = persistReducer(persistConfig, combineReducer);


// export reducers under slices
const store = configureStore({
reducer: persistedReducer,
devTools: process.env.NODE_ENV !== 'production',
preloadedState: loadState(), //call loadstate method to initiate store from localstorage
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
thunk: true,
serializableCheck: false,
}),
});
// handle state update event. Whenever the state will change, this subscriber will call the saveState methode to update and persist the state into the store
store.subscribe(throttle(() => {
saveState(store.getState());
}, 1000));




export default store;


//App.ts
import { persistStore } from 'reduxjs-toolkit-persist';
import { PersistGate } from 'reduxjs-toolkit-persist/integration/react';
import './i18n';


let persistor = persistStore(store);


ReactDOM.render(
<Provider store={store}>
<PersistGate loading={<div>Loading .....</div>} persistor={persistor}>
<HalocarburesRouter />
</PersistGate>
</Provider>,
document.getElementById('ingenierieMdn'));