在Redux中链接多个异步调度

安东尼·钟

我试图以以下方式将多个动作链接在一起:

A.将用户数据发布到数据库

B.使用发布的数据查询Elasticsearch的结果

(我同时做A和B)

B1。使用ES的结果,从两个表B2中查询原始数据库的结果。导航到新页面并更新UI

我现在正在使用thunk来推理我的代码,但是我也发现这种异步模式非常冗长:

export function fetchRecipes(request) {
  return function(dispatch) {
    dispatch(requestRecipes(request))    
    return fetch(url)
      .then(response => response.json())
      .then(json => dispatch(receiveRecipes(request, json))
    )
  }
}

这与“ requestRecipes”和“ receiveRecipes”以及其他动作创建者一样,似乎只需要拨打一个异步电话就可以了。(请求,接收和获取功能)

摘要:当您将2-3个异步操作链接在一起时,它们的输出相互依赖(我需要在可能的情况下作出承诺),是否有一种更有效的方法,而无需为每个异步调用编写3个函数?

我认为必须有一种方法。我正在从Redux文档中进行模式匹配,很快就对我创建的功能不知所措

非常感谢您的反馈!

弗洛朗

您可以使用redux-saga代替redux-thunk来更轻松地实现这一目标。redux-saga使您可以使用生成器来描述您的工作,并且更容易推理。

第一步是描述如何将数据传递给redux而不用担心服务或异步内容。

动作

// actions.js
function createRequestTypes(base) {
  return {
    REQUEST: base + "_REQUEST",
    SUCCESS: base + "_SUCCESS",
    FAILURE: base + "_FAILURE",
  }
}

// Create lifecycle types on `RECIPES`
export const RECIPES = createRequestTypes("RECIPES")

// Create related actions
export const recipes = {
  // Notify the intent to fetch recipes
  request: request => ({type: RECIPES.REQUEST, request})
  // Send the response
  success: response => ({type: RECIPES.SUCCESS, response})
  // Send the error
  error: error => ({type: RECIPES.FAILURE, error})
}

减速器

// reducer.js
import * as actions from "./actions"

// This reducer handles all recipes
export default (state = [], action) => {
  switch (action.type) {
    case actions.RECIPES.SUCCESS:
      // Replace current state
      return [...action.response]

    case actions.RECIPES.FAILURE:
      // Clear state on error
      return []

    default:
      return state
  }
}

服务

我们还需要食谱API。使用redux-saga最简单的方法声明服务时,是创建一个(纯)函数,该函数读取请求作为参数并返回Promise

// api.js
const url = "https://YOUR_ENPOINT";

export function fetchRecipes(request) {
  return fetch(url).then(response => response.json())
}

现在我们需要联系行动和服务。这就是redux-saga发挥作用的地方。

// saga.js
import {call, fork, put, take} from "redux-saga/effects"
import * as actions from "./actions"
import * as api from "./api"

function* watchFetchRecipes() {
  while (true) {
    // Wait for `RECIPES.REQUEST` actions and extract the `request` payload
    const {request} = yield take(actions.RECIPES.REQUEST)

    try {
      // Fetch the recipes
      const recipes = yield call(api.fetchRecipes(request))

      // Send a new action to notify the UI
      yield put(actions.fetchRecipes.success(recipes))
    } catch (e) {
      // Notify the UI that something went wrong
      yield put(actions.fetchRecipes.error(e))
    }
  }
}

function* rootSaga() {
  yield [
    fork(watchFetchRecipes)
  ]
}

就是这样!每当组件发送RECIPES.REQUEST动作时,传奇故事就会连接并处理异步工作流程。

dispatch(recipes.request(req))

令人敬畏的redux-saga是,您可以轻松地在工作流程中链接异步效果并调度动作。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章