gpt4 book ai didi

javascript - 如何使用 redux-toolkit 配置 redux-persist?

转载 作者:行者123 更新时间:2023-12-04 10:02:32 31 4
gpt4 key购买 nike

我已经使用传统的 react-redux 设置配置了 redux-persist,如下所示:

onst persistConfig = {
key: 'root',
storage,
whitelist: ['todos'],
};

const persistedReducer = persistReducer(persistConfig, reducer);

const store = createStore(
persistedReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

const persistor = persistStore(store);

// wrapper
const StateProvider = ({ children }) => {
return (
<Provider store={store}>
<PersistGate loading={<div>Loading...</div>} persistor={persistor}>
{children}
</PersistGate>
</Provider>
);
};
但是,如何使用 redux-toolkit 配置它?
到目前为止,我已经尝试过:
const persistedReducer = persistReducer(persistConfig, todoreducer);
const store = configureStore({
reducer: {
todos: persistedReducer,
},
});

const persistor = persistStore(store);

// wrapper
const StateProvider = ({ children }) => {
return (
<Provider store={store}>
<PersistGate loading={<div>Loading...</div>} persistor={persistor}>
{children}
</PersistGate>
</Provider>
);
};
但是,它不起作用。我无法获得 todos通过 const todos = useSelector(state => state.todos);它返回未定义。

最佳答案

store.js

import {configureStore} from '@reduxjs/toolkit';
import storage from 'redux-persist/lib/storage'
import {combineReducers} from "redux";
import { persistReducer } from 'redux-persist'
import thunk from 'redux-thunk'

const reducers = combineReducers({
//...
});

const persistConfig = {
key: 'root',
storage
};

const persistedReducer = persistReducer(persistConfig, reducers);


const store = configureStore({
reducer: persistedReducer,
devTools: process.env.NODE_ENV !== 'production',
middleware: [thunk]
});

export default store;
索引/App.js
import store from './app/store';
import { PersistGate } from 'redux-persist/integration/react'
import { persistStore } from 'redux-persist'

let persistor = persistStore(store);

<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<App/>
</PersistGate>
</Provider>,

关于javascript - 如何使用 redux-toolkit 配置 redux-persist?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63761763/

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