【发布时间】:2022-01-03 11:12:54
【问题描述】:
我有一个名为saveThing 的操作。在其中,我有参数 thingNoErrors 和 thingWithErrors 。我有一个if statement,如果thingNoErrors 有一个值,那么您只需调用API。我的问题是我不想重复发送constants.SUCCESSFUL 和callback 只是为了减少代码并避免重复。有没有更好的修改方法?
export const saveThing =
({ thingNoErrors = [], thingWithErrors = [], callback = () => {} }) =>
async (dispatch) => {
try {
dispatch({
type: constants.REQUESTING,
});
if (thingNoErrors?.length > 0) {
let formData = new FormData();
Object.keys(thingNoErrors).forEach((fieldName) => {
formData.append(
thingNoErrors[fieldName]?.name,
thingNoErrors[fieldName]?.file
);
});
const response = await axios.post(`${API_URL}/sample/api`, formData);
dispatch({
type: constants.SUCCESSFUL,
payload: {
data: [...response.data, ...thingWithErrors],
},
});
callback('success')
}
dispatch({
type: constants.SUCCESSFUL,
payload: {
data: thingWithErrors,
},
});
callback('success')
} catch (error) {
dispatch({
type: constants.ERROR,
});
}
};
【问题讨论】:
标签: reactjs redux ecmascript-6 react-hooks