Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
React native Can';t改变持续重复状态_React Native_React Redux_Redux Persist - Fatal编程技术网

React native Can';t改变持续重复状态

React native Can';t改变持续重复状态,react-native,react-redux,redux-persist,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

我正在使用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;

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

map
始终使用回调函数的结果创建一个新数组,请查看。在reducer中,您正在应用
映射
函数,但是您没有保留对新数组的任何引用,也没有返回
现有状态
,因此
状态没有变化
,并且您的状态没有被持久化

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

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;
  }
};

希望这会有帮助

你永远不应该改变国家。如果需要更新状态,请创建一个副本,对其进行更新并返回新状态。最可能的情况是,redux persist无法识别状态已更改。以下是如何更新redux状态的常见模式。其中之一是“更新数组中的项”
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;
  }
};