我正在使用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;
Schedule reducer
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 回答
map
总是使用回调函数的结果创建一个新数组,看看here . 在你的reducer中,你正在应用map
函数,但是你没有对新数组进行任何引用并返回existing state
,因此state
没有变化,并且你的状态没有被持久化 .您可以按如下方式更改减速器
希望这会有所帮助!