gpt4 book ai didi

javascript - 在 Redux 中使用 LocalStorage 保持多个状态

转载 作者:行者123 更新时间:2023-11-30 14:53:50 25 4
gpt4 key购买 nike

我需要使用 LocalStorage 在 Redux 存储中保存多个状态。在我的情况下,我已经有了一个工作键,它是驱动程序。还需要与公共(public)汽车和运营商状态有关。

Store.js

import ReduxThunk from 'redux-thunk';
import { createStore, applyMiddleware, compose } from 'redux';
import Reducers from './reducers';
import { loadState, saveState } from '../../utils/localstorage';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

// LOCAL STORAGE FOR DRIVERS, BUSES, CARRIERS

const persistedState = loadState()

const store = createStore(
Reducers,
persistedState,
composeEnhancers(
applyMiddleware(
ReduxThunk
)
)
);

store.subscribe(() => {
saveState({
drivers: store.getState().drivers
});
});

export default store;

localstorage.js

export const loadState = () => {
try {

const serializedDriversState = localStorage.getItem('drivers')

if (serializedDriversState === null) {
return undefined;
}
return JSON.parse(serializedDriversState);
} catch (err) {
return undefined;
}
};

export const saveState = (drivers) => {
try {
const serializedDriversState = JSON.stringify(drivers);
localStorage.setItem('drivers', serializedDriversState)
} catch (err) {
// Ignore errors.
}
}

我正在使用 Dan Abramov 的示例:Redux LocalStorage .

那么如何在 Redux store 中使用 LocalStorage 存储多个状态呢?这是好的方法还是使用像 redux-persist 这样的中间件? ?

最佳答案

我认为,你应该在 store.subscribe 函数中添加 forEach over state,你可以部分保存整个商店。

export const saveState = (key, data) => {
try {
const serialized = JSON.stringify(data);
localStorage.setItem(key, serialized);
} catch (err) {
// Ignore errors.
}
}

store.subscribe(() => {
const state = store.getState();
Object.keys(state).forEach( key => {
saveState(key, state[key])
})
});

关于javascript - 在 Redux 中使用 LocalStorage 保持多个状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47690042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com