访问 redux-persist 中的数据(react native)

Access the datas in redux-persist (react native)

我是react-redux的新手。我正在尝试使用 redux 的 Todo 应用程序。在这里我需要存储数据并在应用程序打开时立即显示它们,为此使用了 redux-persist。它工作正常。我被卡住的那个正在行动。我在这里初始化了 id = 0 。因此,每次应用程序打开时,它都会存储 id = 0 的数据,然后递增。如何引用从 persist 存储的最后一个 id 并在添加新数据时使用它?

App.js

export const persistor = persistStore(store);

class App extends Component<Props> {
  render() {
    return (
      <Provider store={store}>
        <PersistGate loading={<ActivityIndicator />} persistor={persistor}>
          <ToDoApp />
        </PersistGate>
      </Provider>
    );
  }
}

店铺

const persistConfig = {
     key: 'root',
     storage,
     stateReconciler: autoMergeLevel2 
};

const pReducer = persistReducer(persistConfig, rootReducer);

export default (store = createStore(pReducer));

行动

import { ADD_TODO, TOGGLE_TODO } from './actionTypes';

let nextId = 0; // how to initialize nextId as the last id from persisted data?
export const addToDoo = text => ({
  type: ADD_TODO,
  id: nextId++,
  text
});

export const toggleTodo = id => ({
  type: TOGGLE_TODO,
  id
});

到目前为止我还没有使用过 redux-persist,我正在使用 this technique 但这是题外话,你的问题只与 redux.

有关

将 id 分配给新的待办事项不是 action creator 的工作,而是 reducer 的工作。您的操作可能如下所示:

const addTodo = text => ({
  type: ADD_TODO,
  text,
})

那是在必须驻留的减速器中 nextId。在启动(或页面重新加载)时,它将为 0 或存储在 localStorage 中的值。每次出现 ADD_TODO 动作时它都会增加:

const initialState = {
  nextId: 0,
}

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      //...
    case 'TOGGLE_TODO':
      //...
    default:
      return state
  }
}

我看到 redux-persist 完成了将状态序列化到存储(浏览器的 localStorage 和 React-Native 的 AsyncStorage)并在启动时检索它的所有魔法。作为参考,这就是我为纯 React 应用程序所做的(使用 localStorage 的旧方法):

  • 在根index.js中,在createStore之后,我从存储中获取值:const nextIdFromLS = storage.getItem("nextId")
  • 如果此值存在,我会启动一个操作来设置此 nextId 值 store.dispatch(setNextId(nextIdFromLS))
  • action SET_NEXT_ID 使 reducer 使用来自 localStorage
  • 的 nextId 更新状态
  • 下次添加待办事项时,在 case "ADD_TODO": 内,我会按预期存储新的待办事项,但我也会 运行 localStorage.setItem("nextId", this.state.nextId++) 以便我们存储值并且我们可以刷新页面