从action创建者正确访问error对象(来自后台)的方法取决于使用的前端框架或库。一般情况下,后台返回的错误信息会包含在响应的数据中,可以通过以下步骤来访问error对象:
fetch
、axios
等工具发送异步请求。response.data
或response.body
来访问数据。error
属性来存储错误信息。以下是一个示例代码,展示了如何从action创建者中访问后台返回的error对象:
import axios from 'axios';
// action创建者
export const fetchData = () => {
return (dispatch) => {
axios.get('/api/data')
.then((response) => {
// 请求成功
dispatch({
type: 'FETCH_SUCCESS',
payload: response.data
});
})
.catch((error) => {
// 请求失败
dispatch({
type: 'FETCH_ERROR',
error: error.response.data
});
});
};
};
// reducer
const initialState = {
data: null,
error: null
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'FETCH_SUCCESS':
return {
...state,
data: action.payload,
error: null
};
case 'FETCH_ERROR':
return {
...state,
data: null,
error: action.error
};
default:
return state;
}
};
在上述示例中,FETCH_ERROR
action的error
属性存储了后台返回的错误信息。在reducer中,可以根据需要对错误进行处理,例如显示错误提示或进行其他操作。
请注意,以上示例中的代码是基于axios库和Redux状态管理库的假设。实际上,具体的实现方式可能因使用的框架或库而有所不同。
领取专属 10元无门槛券
手把手带您无忧上云