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

1bqhqjot  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(155)

我有一个Redux应用程序,它使用redux-persist来存储auth jwt token。该应用程序将从redux存储中获取token,并将其放入HTTP Authorization标头。
这里的问题是,每当我在另一个选项卡中登录到其他用户时,redux存储不会使用新登录的用户令牌进行更新。(尽管localStorage使用新登录的用户令牌进行更新)
所以我想知道是否有一个最佳实践来做到这一点,通过设置一些选项redux-persist
或者我需要添加一个localStorage侦听器来更新redux存储每当有一个localStorage更改?
我希望我的解释是可以理解的。
谢谢你

de90aj5v

de90aj5v1#

不,没有内置的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-syncreduxmiddleware

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};

please see this link for more info

相关问题