是否有 redux-persist API 可以将 localStorage 更改同步到 redux-persist?

问题描述 投票:0回答:1

我有一个

Redux
应用程序,它使用
redux-persist
来存储身份验证 jwt 令牌。 应用程序将从 redux 存储中获取令牌并将其放入 HTTP
Authorization
标头。

这里的问题是,每当我在另一个选项卡中登录其他用户时,redux 存储都不会使用新登录的用户令牌进行更新。 (尽管

localStorage
已使用新登录的用户令牌进行更新)

所以我想知道是否有最佳实践通过将一些选项设置为

redux-persist
来做到这一点?

或者我是否需要添加一个 localStorage 侦听器来在 localStorage 发生更改时更新 redux 存储?

我希望我的解释是可以理解的。

谢谢你

reactjs redux local-storage redux-persist
1个回答
1
投票

不,没有内置 API!

您可以使用

storage
事件:

import { legacy_createStore as createStore,Store, applyMiddleware} from "redux";
import reducer from "./reducer";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import persistStore from "redux-persist/es/persistStore";


const persistConfig = {
    key:"root",
    storage:storage,
    blacklist:["loading"]
}
 
const persistedReducer = persistReducer( persistConfig , reducer );
const store = createStore(
    persistedReducer, 
    {counter:0}, // initial state
);
 
const persistor = persistStore(store);
export {store , persistor};


/* this event update state when storage changed! */
window.addEventListener('storage',(e)=>{
    const persistData = JSON.parse(localStorage.getItem('persist:root'));
    const newCounterValue = parseInt(persistData.counter);
    console.log(newCounterValue);
    store.dispatch({type:'SET_VALUE',payload:newCounterValue})
})

其他选项是

redux-state-sync
套件。
redux-state-sync
middleware
redux

npm i redux-state-sync

在此示例中,当计数器在

localstorage
中更改时,所有选项卡都将收到新的状态值!

import { legacy_createStore as createStore,Store, applyMiddleware} from "redux";
import reducer from "./reducer";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import persistStore from "redux-persist/es/persistStore";

import {
    createStateSyncMiddleware,
    initMessageListener,
} from "redux-state-sync";
 
const persistConfig = {
    key:"root",
    storage:storage,
    blacklist:["loading"]
}
 
const persistedReducer = persistReducer( persistConfig , reducer );
const store = createStore(
    persistedReducer, 
    {counter:0}, // initial state
    applyMiddleware(createStateSyncMiddleware())
);

initMessageListener(store);
 
const persistor = persistStore(store);
export {store , persistor};

请查看此链接以获取更多信息

© www.soinside.com 2019 - 2024. All rights reserved.