reactjs - 为什么 Redux-Persist 不持久化存储
问题描述
大家好,我在搞乱反应(准确地说是redux)并遇到了一个问题。当我刷新页面时,redux 商店的一切都恢复到初始值,我用谷歌搜索了这个问题,发现我必须使用redux-persist
. 但是即使这样也不起作用,我认为问题在于我如何配置 redux-persist 但我可能是错的。下面的代码是我如何进行 redux-persist 配置的。
// configureStore.js
import { createStore, applyMiddleware } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import rootReducer from "../reducers/index";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";
const persistConfig = {
key: "root",
storage,
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
export const store = createStore(
persistedReducer,
composeWithDevTools(applyMiddleware(thunk))
);
export const persistedStore = persistStore(store);
下面的代码显示了我是如何制作rootReducer
.
// index.js
import { combineReducers } from "redux";
import { reducer as formReducer } from "redux-form";
import authReducer from "./auth";
import messageReducer from "./message";
import chatroomReducer from "./chatroom";
import { LOGOUT_SUCCESS } from "../actions/authTypes";
const apiReducer = combineReducers({
authReducer,
messageReducer,
chatroomReducer,
form: formReducer,
});
const rootReducer = (state, action) => {
if (action.type === LOGOUT_SUCCESS) {
state = undefined;
}
return apiReducer(state, action);
};
export default rootReducer;
下面的代码是index.js
创建 React 应用程序时的代码。
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { PersistGate } from "redux-persist/integration/react";
import { Provider } from "react-redux";
import { store, persistedStore } from "./Redux/configureStore";
ReactDOM.render(
<Provider store={store}>
<PersistGate loading={null} persistor={persistedStore}>
<React.StrictMode>
<App />
</React.StrictMode>
</PersistGate>
</Provider>,
document.getElementById("root")
);
reportWebVitals();
谁能告诉我我的代码有什么问题?如果您需要更多信息,请告诉我。
解决方案
尝试配置白名单,您必须在其中指明要存储哪些减速器。请记住在将减速器添加到列表之前导入它们
import navigation from "./reducers/navigation";
// WHITELIST
const persistConfig = {
key: 'root',
storage: storage,
whitelist: ['navigation'] // only navigation will be persisted
};
推荐阅读
- java - 如何使用 CP Optimizer 为提货和送货操作建模容量限制?
- facebook - 为什么以及如何在 aws cognito 上检索使用 facebook 登录的用户信息?
- python - Python Asyncio如何从队列中连续运行任务/协程
- apache-camel - Apache Camel - 类型转换期间的错误或误解行为
- javafx - javafx中如何将一个变化的长数字绑定到一个标签上,使标签不断更新
- python - 在用户输入的某些点处切片和添加换行符的正确方法
- c++ - std::unordered_set::load_factor,为什么浮点数而不是双精度数?
- list - 如何为我的 3D 列表中的每个元素 = 1 分配一个随机数?
- laravel - 根据用户角色在侧边栏中显示/隐藏菜单(Laravel/Spatie)
- firebase-realtime-database - 使用 MAX30100 将心率和血氧饱和度数据推送到 Firebase 时出现问题