如何从Redux持久存储中读取(localstorage)

时间:2020-02-22 19:48:32

标签: javascript reactjs redux redux-persist

我有一个redux持久配置,如下所示:

const persistConfig = {
    key: 'persistedStore',
    storage: storage,
    transforms: [expireIn(expireTime, expirationKey, []), encryptor],
    whitelist: ['reducer1','reducer2','reducer3', 'reducer4']
};

因此localStorage密钥类似于“ persist:persistedStore”。

我已经尝试过这样读取存储: let user = localStorage.getItem('persist:persistedStore'),这给了我一些回馈,但 当我执行类似的操作:user.reducer1时,始终返回未定义。 console.log(localStorage.getItem('persist:persistedStore'),返回以下内容:存储中的数据:

{"reducer1":"\"U2FsdGVkX1/PRA7nYWyo2/SVOlbMXs0z50XKvWmhxhUDW+DaQ9FU9jIRnVTSLpwzpS5NCWC+xX3V2TWBNGFzUA==\"","reducer3":"\"U2FsdGVkX183kEvgTl8/hC450C9iyVJh++m2ptQlqbFBskhU2B5l43Hyf2azCeF7xe4KcDqzXoO6Zhe7qQV8aaX+tOpPqQrzhS9hjsD8n1Gkbx5c/g0LfzBXnv+zh88ztZBERj5/p51uEmn/yI5TBvdBdtSoeQNTylFTlkIBJSVJtjovl5uNN3Iqc6Pj0WOJTNMnJaQsT/WjWiuODz2fIXgWpiny4Rj3Fek10m/3RVAn45pPrKlZoTFot8ih5oyz8v0oUBPbOcsa+sxfRTaM0AL7Lxud1mr3KFt5gy/9GDGTxukLfI0Z9jsaLH+0p1wicgUZO0pUgPuiF5KfU+WGLxxCbDheFwFU71j/welwyTvG1k6Jjbrq5/SIV2Oh1hQJlZ5G+ODRRwHyPPh07eq5kntUFwfGhxY+xVqB0EYh04+K5nqoauaQVZeRPHlvt7djiuh61BlycyINWBBYugpzES2UEbT2Q7Dtt65087+ST6/KbAEnTsOaJ+xy1GdyYNobE5XkcUXnF+vfv+Bn/6V9+1wHpnVYTGPBWIJ6xlN+6s4tkNp+nC7bGQ6r8G8boUnqA9ANQHX4w2S+jr7ysTa5udmQ1Ch7YC/Efb++ywdIUWs7tqZpeSngRzwTQ/jtzPcAoKD4zjEWZNCyyjAXa1P/rpv++KcnWyHbw7VfSBd0BXo=\"","reducer2":"\"U2FsdGVkX19nPr02OWgj71q600tUk0PU5hYZVm7G+pAcByNvztMt7C9BqFLCYyOBLzfi0l/UdPntltGPoKEKpguIis2chKHPyX0c2c7owNQ=\""

1 个答案:

答案 0 :(得分:1)

由于localStorage将数据持久存储在字符串中,因此您需要先将JSON字符串化后再存储,然后在检索时对其进行解析。

// storage
const storage = { "reducer1": { "someKey": "Some Data" } }
localStorage.setItem('persistedStore', JSON.stringify(storage))
// retrieval
const retrievedStoreStr = localStorage.getItem('persistedStore') // this is a string
const retrievedStore = JSON.parse(retrievedStoreStr) // this will be a JSON object
const reducer1 = retrievedStore.reducer1 // should now have your reducer