您可以使用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
动作时,saga 就会连接并处理异步工作流。
dispatch(recipes.request(req))
令人敬畏的redux-saga
是,您可以在工作流程中轻松链接异步效果和调度操作。