如何持久化状态的redux切片



状态已经设置,但我不完全确定为什么我的extraReducers状态在页面刷新时没有持久化到存储。我只为reducers测试了一个状态设置器,它在页面刷新时保持得非常好。

Store.ts

import storage from "redux-persist/lib/storage";
import {
persistStore,
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from 'redux-persist'
import { createWhitelistFilter } from 'redux-persist-transform-filter';
import { configureStore, combineReducers } from '@reduxjs/toolkit'
import { blockchainSlice } from 'slices'
const persistConfig = {
key: "root",
version: 1,
storage,
whitelist: ['blockchain']
}
const persistedReducer = persistReducer(persistConfig, combineReducers({
blockchain: blockchainSlice.reducer
}))
export const store = configureStore({
reducer: persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
});
export const persistor = persistStore(store)
export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;

区块链切片.ts

import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';
import { Contract } from "web3-eth-contract";
import Web3 from "web3";
import { RootState } from 'root';
declare let window: any;
export interface BlockchainState {
contract: Contract | null,
ethWeb3: {
connected: boolean,
instance: Web3 | null,
walletAddress: string | null
}
}
const initialState: BlockchainState = {
contract: null,
ethWeb3: {
connected: false,
instance: null,
walletAddress: null
}
}
export const initWeb3Instance = createAsyncThunk(
'blockchain/initWeb3', async (thunkApi) => {
if (window.ethereum) {
await window.ethereum.send('eth_requestAccounts')
let web3 = new Web3(window.ethereum)

let address = await web3.eth.getAccounts().then(addr => addr[0].toLowerCase())
return { instance: web3, walletAddress: address }
} else {
alert('Please install Metamask!')
}
}
)
export const blockchainSlice = createSlice({
name: 'blockchain',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(initWeb3Instance.fulfilled, (state, { payload }: any) => {
state.ethWeb3.connected = true
state.ethWeb3.instance = payload.instance
state.ethWeb3.walletAddress = payload.walletAddress
})
},
})
export default blockchainSlice

我使用useAppSelector来确认状态已设置,但查看本地存储,没有任何变化,并且在页面刷新时它不会持续。非常困惑,希望再次关注这里可能存在的问题。非常感谢。

const { connected, instance, walletAddress } = useAppSelector((state) => state.blockchain.ethWeb3)

当我们刷新redux应用程序中的页面时会发生什么

当你刷新页面时,你正在用初始状态重新创建一个存储,所以如果你想在刷新时保留一些切片信息,你需要将它们存储在中

我应该使用哪个存储来持久化切片

根据您的平台和信息隐私,您可以使用不同的解决方案。有关应用程序上钱包地址等基本信息,您可以使用本地存储。您只能放置可串行化的对象。似乎您的实例是一个类实例,所以您不能串行化

如何在本地存储中保持冗余状态

您可以使用redux-persistent将切片持久化到本地存储中,并在重新加载页面时使用它们https://github.com/rt2zz/redux-persist

仅将可串行化的对象置于状态

如果ethWeb3.instance是类实例而不是可序列化对象,则这是错误的模式。状态应该是可序列化的,因此不能设置类。这就是为什么你不能坚持

用redux把类实例放在哪里

例如,我认为您的实例可以生活在中间件中。

相关内容

  • 没有找到相关文章