无法更改持久的redux状态

时间:2018-04-05 17:16:11

标签: react-native react-redux redux-persist

我正在使用Redux Persist来保存应用程序的状态,以便在关闭并再次打开时它是相同的。初始状态已成功保存,但我似乎无法通过操作更新持久状态。我的代码如下:

App.js

import React from "react";
import { createStore } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import reducers from "./src/reducers";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import Router from "./src/Router";

const persistConfig = {
  key: "root",
  storage,
  debug: true
};

const persistedReducer = persistReducer(persistConfig, reducers);

const store = createStore(persistedReducer);
const persistor = persistStore(store);

const App = () => (
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <Router />
    </PersistGate>
  </Provider>
);

export default App;

安排减速机

import { strings } from "../../locales/i18n";
import * as types from "../actions/types";

const initialState = strings("schedule.list").map((item, index) => {
  return {
    key: index.toString(),
    title: item.title,
    time: item.time,
    location: item.location,
    description: item.description,
    isFavorite: false
  };
});

const scheduleReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.TOGGLE_FAVORITE:
      state.map(schedule => {
        if (schedule.key === action.id) {
          return (schedule.isFavorite = !schedule.isFavorite);
        }
      });
      return state;
    default:
      return state;
  }
};

export default scheduleReducer;

我可以看到isFavorite的状态在我调用操作时发生了变化,但是当我重新加载应用程序时,它不会被持久化。这可能是什么问题?

1 个答案:

答案 0 :(得分:1)

map总是使用回调函数的结果创建一个新数组,看看here。在您的reducer中,您正在应用map函数,但您没有对新数组进行任何引用并返回existing state,因此state中没有任何更改,您的状态为不被坚持。

您可以按如下方式更改减速器

const scheduleReducer = (state = initialState, action) => {
  switch (action.type) {
  case types.TOGGLE_FAVORITE:
    cont updatedState = state.map(schedule => {
      if (schedule.key === action.id) {
        return { 
           ...schedule,
           isFavorite: !schedule.isFavorite 
        };
      }
      return schedule;
    });
    return updatedState;
  default:
    return state;
  }
};

希望这会有所帮助!