在 React with Redux 中,我应该什么时候将数据保存到后端

In React with Redux, when should I save data to back end

在React with Redux中,当有一些用户操作时,例如在facebook中,用户添加了一些评论,我会调用dispatch()将添加操作发送到redux store,但我应该什么时候回调end API 将这些数据保存到数据库?我需要和 dispatch() 一起做吗?

谢谢

一个解决方案是使用 redux-thunk(或类似的)中间件包将您的 API 逻辑转移到 thunk

使用 thunk 允许您将特殊类型的 actions 视为函数,这意味着您可以使用特定的与动作相关的逻辑来扩展普通动作。你给出的需要序列化你的状态的例子是 redux-thunk 的一个很好的用例。

您应该注意,与 reducer 不同,thunk 明确支持通过 getStatedispatch 函数获取状态和分派后续操作。

下面是一个 ES6 示例,展示了这种多用途 thunk 的外观。

为了演示 getState() 方法,仅当 redux 状态 shouldSave 值为真时,新项目才会通过 api 保存。

我还会使用 async/await 语法来确保 api 调用成功 调度本地 redux 操作之前。

Thunk 示例 - 添加新项目

import api from './api'

export const addNew = async (item) => {
  return (dispatch, getState) => {
    try{
      const state = getState()
      if(state.shouldSave){
        await api.save(item)
      }
      dispatch({
        type: ITEM_ADD_NEW,
        data: item
      })
    }catch(err){
      const error = new Error("There was a problem adding the new item")
      error.inner=err
      throw(error)
    }
  }
}