我们有一个多个定制的Reaction文件输入组件(假设有4个不同的输入文件部分).需要为内部触发动作的每个组件上传文件,并调用API调用将文件上传到服务器.
所以这里的问题是所有文件上传的api调用都是一样的.我们需要对动作进行排序(第一个文件上传动作,第一个解析,第二个解析,等等),这样所有的api都将按顺序执行(根据我们的项目要求,我们需要将一个API响应头xsrf令牌作为请求头传递给下一个调用api).
以下是我try 过的代码.
import { take, actionChannel, call, put, fork, takeEvery, takeLatest } from 'redux-saga/effects';
import { AnyAction } from 'redux';
import { ServicesType } from '../services/types';
import { uploadLossOfAccountMaleSuccess, uploadLossOfAccountFemaleSuccess fetchDataFailure, UploadExistingAccountMaleSuccess, UploadExistingAccountFemaleSuccess} from './actions';
import {UPLOAD_ACCOUNT_LOSS_REQUEST_MALE, UPLOAD_ACCOUNT_LOSS_REQUEST_FEMALE, UPLOAD_ACCOUNT_EXIST_REQUEST_MALE, UPLOAD_ACCOUNT_EXIST_REQUEST_FEMALE} from './actionTypes';
// services are written for making an axios api calls
type Services = Pick<ServicesType, 'FileUpload'>;
function uploadLossOfAccount(services: Services, gender: string) {
return function* (action: AnyAction) {
try {
//postData is function which makes an axios call
const data = yield call(services.FileUpload.postData, action.payload);
gender=="male"?yield put(uploadLossOfAccountMaleSuccess(data)): yield put(uploadLossOfAccountFemaleSuccess(data));
} catch (error) {
// Dispatch failure action
yield put(fetchDataFailure(error.message));
}
}
function UploadExistingAccount(services: Services, gender: string) {
return function* (action: AnyAction) {
try {
//postData is a function that makes an axios call
const data= yield call(services.FileUpload.postData, action.payload);
gender=="male"? yield put(UploadExistingAccountMaleSuccess(data)): yield put(UploadExistingAccountFemaleSuccess(data));
} catch (error) {
// Handle error if needed
}
}
//sequencing actions
**function* watchRequests(services:Services) {
// Create an action channel for actions
const requestChannel = yield actionChannel([UPLOAD_ACCOUNT_LOSS_REQUEST_MALE, UPLOAD_ACCOUNT_LOSS_REQUEST_FEMALE, UPLOAD_ACCOUNT_EXIST_REQUEST_MALE, UPLOAD_ACCOUNT_EXIST_REQUEST_FEMALE]);
while (true) {
// Take the next action from the channel
const action = yield take(requestChannel);
switch (action.type) {
case UPLOAD_ACCOUNT_LOSS_REQUEST_MALE:
yield call(uploadLossOfAccount, services, "male");
break;
case UPLOAD_ACCOUNT_LOSS_REQUEST_FEMALE:
yield call(uploadLossOfAccount, services, "female");
break;
case UPLOAD_ACCOUNT_EXIST_REQUEST_MALE:
yield call(UploadExistingAccount, services, "male");
break;
case UPLOAD_ACCOUNT_EXIST_REQUEST_FEMALE:
yield call(UploadExistingAccount, services, "female");
break;
//other actions
}
}
}**
function* fileUploadSaga(services:Services):any{
return [yield watchRequests(services]
}
export default fileUploadSaga
rootSaga.js
export default function* rootSaga() {
const totalSagas=[...fileUploadSaga, ...remainingSagas]
yield all(totalSagas);
}
我怀疑fileuploadSaga功能有问题. API调用自身不是通过上述代码进行的.请提出任何更改,使其正常工作.我无法发现我在哪里犯了错误.请帮助在这种情况下,使所有的行动执行顺序.