【发布时间】:2021-08-27 12:21:28
【问题描述】:
我在获取请求时遇到了这个问题,这是我的 axios 代码:
export const fetchNotifications = (id, key) => dispatch => {
dispatch( fetchNotificationsStarted() );
axios.get(uri + `/app/notifications/${id}?key=${key}`).then(result => {
console.log("Axios:",result.data);
dispatch( fetchNotificationsSuccess(result.data) );
}).catch(error => {
dispatch( fetchNotificationsFailure(error.message) );
});
}
我从 api 获取对象数组,但所有对象都设置为 {id : 0,...} 并且此 id 是我的 sql 数据库中的自动数字字段。你以前有过这种情况吗?我该如何解决?我需要这个特定的字段来提出个人请求
console.log 输出:
邮递员 api 响应:
[
{
"id": 1,
"created_at": "2021-04-23T14:49:47.000Z",
"title": "...",
"body": "...",
"watch": 1
},
{
"id": 2,
"created_at": "2021-04-23T15:17:24.000Z",
"title": "...",
"body": "...",
"watch": 1
}
]
我的动作函数:
export const fetchNotificationsSuccess = notifs => ({ type : actions.FETCH_NOTIFICATIONS_SUCCEED, payload : notifs });
这是我的减速器:
export const reduceNotifications = (state = initialState, action) => {
switch(action.type) {
case actions.FETCH_NOTIFICATIONS_SUCCEED : return ({
...state,
FETCH_REQUEST_STARTED : false,
FETCH_REQUEST_FAILURE : false,
FETCH_REQUEST_SUCCEED : true,
notifications : [...action.payload],
MESSAGE : ''
});
default: return state;
}
}
【问题讨论】:
-
如果您正确检索您的 api,那么问题出在您的 API,而不是您的反应代码。
-
您是否查看了浏览器开发工具或其他检查器来查看从 API 返回的实际数据?如果这些都是零,那么 API 就是问题所在。
-
是的,从邮递员和浏览器我得到这些字段的值是 1, 2 而不是 0,0
-
你有为 axios 定义的变换函数吗?恕我直言,要么是转换中间件,要么是 cors 问题
-
当您执行
console.log("Axios:",result.data);时,控制台会收到对对象result.data的引用,并且在您单击三角形之前不会读取其内容。因此,控制台中显示的数据可能已被代码中的稍后步骤更改,并且不一定反映您调用console.log时的状态。将其替换为console.log("Axios:",JSON.stringify(result.data,null,2));以查看实际数据,或者在console.log之后设置断点
标签: javascript reactjs redux axios redux-thunk