【问题标题】:Save data in localstorage after call proper action. React & Redux调用适当的操作后将数据保存在本地存储中。反应和还原
【发布时间】:2018-04-23 22:31:34
【问题描述】:

我将在本地存储中保存一些数据,但仅在调用 UPDATE_POST 操作之后。现在我通过以下方式在 index.js 中应用 localstorage:

store.subscribe(throttle(() => {
  post: saveState(store.getState().post);
}, 1000))

它每秒将数据保存在本地存储中。但我的目标是仅在 updatePost 操作后保存它。可以用中间件实现吗,怎么写?

我的减速机:

const Post = (state = {}, action) => {
  switch (action.type) {
    case 'INIT_POST':
        ..... some code
    case 'UPDATE_POST':
        ... some code
    default:
      return state
  }
};

我的行动:

export const updatePost = (...items) => ({
    type: 'UPDATE_POST',
    items
});

【问题讨论】:

  • updatePost 是异步函数吗?
  • 是的,它是异步函数

标签: reactjs redux local-storage react-redux middleware


【解决方案1】:

我为此使用 Redux-thunk (https://github.com/gaearon/redux-thunk) - 它允许您编写返回函数而不是动作的动作创建器 - 允许您在动作中执行异步任务,然后点击减速器。

使用 redux-thunk 你可以调用一个异步函数(下面例子中的 performSomeAsyncFunction() ),获取响应,处理它(比如下面的 saveDataToLocalStorage() 虚拟函数),然后点击 reducer 来更新你的状态:

export const startUpdatePost = (...items) => {
  return (dispatch) => {
    return performSomeAsyncFunction(...items).then((response) => {
      dispatch(updatePost(...items));
      saveDataToLocalStorage()

    });
  };
};
  • 别忘了还要处理上面异步函数的失败

【讨论】:

  • 很好的答案,非常简洁
猜你喜欢
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 2022-01-25
  • 2014-07-07
相关资源
最近更新 更多