【问题标题】:Axios is setting id to zeroAxios 将 id 设置为零
【发布时间】: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


【解决方案1】:

我发现了我的错误,在我的模态组件代码的某个地方,我错误地使用了这样的东西:

const selected = ntf.find(elem => elem.id = selected_id);

将所有内容都变为零...很容易修复:

const selected = ntf.find(elem => elem.id === selected_id);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2018-05-24
    • 2011-10-12
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多