我创建了一个上传器来上传CSV文件,该文件会转换为json并发送到API。
如果数据无效,API将进行验证,并且返回我在调试器中看到的响应:
{"success":false,"errorCode":"880ddb963e40","errorMessage":"There are Ids which do not exist in system"}
我的用户界面输出一条通用消息,表明我的减速器存在如下所示的问题:
import {
PUT_UPLOAD_CSV,
PUT_UPLOAD_CSV_SUCCESS,
PUT_UPLOAD_CSV_FAILURE
} from 'constants/BulkUploads/ActionTypes';
const INIT_STATE = {
uploadLoader: false,
uploadResponse: '',
uploadError: ''
}
export default (state = INIT_STATE, action) => {
switch (action.type) {
case PUT_UPLOAD_CSV: {
return {
...state,
uploadLoader: true,
uploadResponse: '',
uploadError: ''
}
}
case PUT_UPLOAD_CSV_SUCCESS: {
return {
...state,
uploadLoader: false,
uploadResponse: 'CSV file uploaded successfully',
uploadError: ''
}
}
case PUT_UPLOAD_CSV_FAILURE: {
return {
...state,
uploadLoader: false,
uploadResponse: '',
uploadError: 'An error occurred uploading CSV file, please check the data and try again.'
}
}
default:
return state;
}
}
我希望我的reducer uploadError
句柄能够返回API errorMessage而不是我的默认API,以便使错误更具体,和/或将错误代码用作查找以显示适当的消息。
如果有人可以协助或指出一些文档。
更新-添加我的操作
import {
PUT_UPLOAD_CSV,
PUT_UPLOAD_CSV_SUCCESS,
PUT_UPLOAD_CSV_FAILURE,
} from 'constants/BulkUploads/ActionTypes';
export const putUploadCSV = (payload) => {
return {
type: PUT_UPLOAD_CSV,
payload
};
};
export const putUploadCSVSuccess = (payload) => {
return {
type: PUT_UPLOAD_CSV_SUCCESS,
payload
}
};
export const putUploadCSVFailure = (payload) => {
return {
type: PUT_UPLOAD_CSV_FAILURE,
payload
};
};
我的index.js
{uploadError ?
{uploadError}
:
{uploadResponse}
}
SAGA
function* putUploadCSVRequest(params) {
try {
const response = yield call(putUploadCSV, params.payload);
yield put(putUploadCSVSuccess(response));
} catch (error) {
console.error(error);
yield put(putUploadCSVFailure(error));
}
}
答案 0 :(得分:1)
您仅在给定功能中使用action.type
。您可能会很好地使用另一个键,最好是类似action.data
或action.payload
之类的键来识别PUT_UPLOAD_CSV_FAILURE
动作的不同类型,并相应地调整减速器。
要根据您的特定情况为您提供确切的解决方案,我可能需要了解您如何调度操作。
更新:
由于您使用的是操作创建者putUploadCSVFailure
,因此可以将操作创建为
putUploadCSVFailure(response.errorMessage)
在HTTP客户端的捕获或响应中(axios?fetch?xhr?)
现在,有效负载为errorMessage,因此将reducer更新为
case PUT_UPLOAD_CSV_FAILURE: {
return {
...state,
uploadLoader: false,
uploadResponse: '',
uploadError: action.payload || 'An error occurred uploading CSV file, please check the data and try again.'
}
}
答案 1 :(得分:0)
由于我不确定您如何调用该操作,因此我可以给您一个提示,以帮助您解决问题。
您可以将message参数传递给操作,然后在化简器中使用它。
行动电话:
this.props.onUploadError({type: PUT_UPLOAD_CSV_FAILURE, errorMessage: jsonData.errorMessage});
Reducer案例声明修改:
case PUT_UPLOAD_CSV_FAILURE: {
return {
...state,
uploadLoader: false,
uploadResponse: '',
uploadError: action.errorMessage
}
}
答案 2 :(得分:0)
您可以添加检查,以确保api发送错误,然后显示api错误或显示自定义错误。例如
const customError = 'An error occurred uploading CSV file, please check the data and try again.'
// in the reducer, assuming action.payload has response
uploadError: action.payload.errorMessage || customError