繁体   English   中英

如何在调用API服务器时从Redux的axios响应中的对象中删除某些属性

[英]How to delete certain properties from an object in an axios response in redux while calling an API server

我正在从我的redux项目中调用API服务器,我想在其中提取数据.API中的数据格式如下所示:

const defaultData = {
  categories: [
      {
        name: 'react',
        path: 'react'
      },
      {
        name: 'redux',
        path: 'redux'
      },
      {
        name: 'udacity',
        path: 'udacity'
      }
  ]
}

因此,在我的redux “ Actions”中 ,我使用axios进行API调用。下面给出了actions文件:

import axios from 'axios';
export const FETCH_CATEGORIES = 'fetch_categories';

let token;
if (!token)
  token = localStorage.token = Math.random().toString(32).substr(-8);
const API = 'http://localhost:3001';
const headers = {
                  'Accept' : 'application/json',
                  'Authorization' : 'token'
}

export function fetchCategories() {
  const URL = `${API}/categories`;
  const request = axios.get(URL,{headers});

  return dispatch => {
        return request.then((data) => {
          dispatch({
            type : FETCH_CATEGORIES,
            payload : data
          })
        })
  }
}

我试图将API调用的结果保存在我的reducer中的应用程序状态中。类别的Reducer看起来像这样:

import _ from 'lodash';
import { FETCH_CATEGORIES } from '../actions/categories_action';

export default function(state={}, action) {
    switch(action.type) {
      case FETCH_CATEGORIES:
        return {categories: {...state.categories, ...action.payload}};

        default:
          return state;
    }
}

我正在使用combinedReducers()将索引文件中的所有reducer合并在一起,如下所示:

import { combineReducers } from 'redux';
import PostReducer from './PostsReducer';
import CategoriesReducer from './CategoriesReducer';

const rootReducer = combineReducers({
    loading: false,
    posts: PostReducer,
    categories: CategoriesReducer
});

export default rootReducer;

然后,在我的组件中,我试图显示状态数据。 因此,当我尝试console.log类别状态的值时,会得到如下图所示的内容:

类别的价值

但是我只想要获得三个类别的Categories属性(我想省略config,headers,request属性)。 我什至尝试过类似的命令: console.log(this.props.categories.data.categories) ,但这给了我一个不确定的值。 谁能帮我这个忙吗?

那是因为这一行{categories: {...state.categories, ...action.payload}};

将其更改为{categories: [...state.categories, ...action.payload.data.categories]};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM