首页 > 解决方案 > Axios 将 id 设置为零

问题描述

我在获取请求时遇到了这个问题,这是我的 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;
      }
   }

标签: javascriptreactjsreduxaxiosredux-thunk

解决方案


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

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

将所有内容都变为零......很容易通过以下方式修复:

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

推荐阅读