React-persist 不是持久状态

React-persist is not persisting state

我正在尝试在我的 reactjs 应用程序中实现 redux-persist,我正在尝试保留用户信息,但每当我刷新所有信息时,所有信息都会被清除,我会被重定向到登录页面。

store.js

import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";
import rootReducer from "./state/reducer";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";

const persistConfig = {
  key: "primary",
  storage,
  whitelist: ["user", "artist"],
  blacklist: ["alerts"],
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

const middleWare = [thunk];
const initialState = {};

export const store = createStore(
  persistedReducer,
  initialState,
  composeWithDevTools(applyMiddleware(...middleWare))
);

export const persistor = persistStore(store);

index.js 所有减速器

import { combineReducers } from "redux";
import artistReducer from "./artistReducer";
import userReducer from "./userReducer";
import alertReducer from "./alertReducer";

export default combineReducers({
  artist: artistReducer,
  user: userReducer,
  alerts: alertReducer,
});

App.js

import { persistor, store } from "./store";
import { PersistGate } from "redux-persist/integration/react";

function App() {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <div style={{ backgroundColor: "grey" }}>
          <Router>
            <Fragment>
              <Navbar></Navbar>
              <Alerts></Alerts>
              <Switch> ...{ code continues }

在这里我可以看到我的数据,但在刷新时它会被清理干净

在探索互联网数小时后,我发现这个问题锁定在 github [ https://github.com/rt2zz/redux-persist/issues/826#fromHistory ] 并且 hackrit 对此发表了很多投票评论,其中指出 “嗨,大家好, 我找到了解决这个问题的方法。 (可能不适用于所有情况,但对我有用)。 问题是由我的减速器中的默认 return 引起的,我 returned {...state}。 一旦我将默认 return 更改为 return 状态,一切都会按预期工作。”这个建议对我有用。

在我的情况下,同样的问题在更新 expo 版本后发生。

解决方案:

// import FSStorage from "redux-persist-expo-fs-storage";
import FSStorage from "redux-persist-fs-storage";
/*
Import change
*/
const primary = {
key: "root",
timeout: 0,
version: 1,
keyPrefix: "",
storage: FSStorage(),
stateReconciler: autoMergeLevel2, // see "Merge Process" section for details.
};

添加键前缀:“”,在配置中。 希望这个解决方案对其他人有用。