【问题标题】:Spread array of objects to array of objects react将对象数组传播到对象数组反应
【发布时间】:2019-08-24 16:05:48
【问题描述】:

我正在使用带有 react 的 redux,我正在尝试将从我的 api 获取的对象数组附加到我的 redux 状态,这是一个对象数组

这是我的减速机...

import { GET_BOOKS } from "../actions/types";
const initialState = {
  books: [
 0:{},
 1:{},
]
};

export default function(state = initialState, action) {
  switch (action.type) {
    case GET_BOOKS:
      console.log(action.payload.results);
      return { ...state };
    default:
      return state;
  }
}

我的 api 正在返回

results : [
0: {somevalue},
1: {somevalue}
]

我不知道如何将值分散到一个新数组中。

【问题讨论】:

  • 您对initialState 的声明存在语法错误。请修复您问题中的语法错误(最好是格式错误),以便我们弄清楚您实际在问什么。还请说明您想要什么,而不是试图用您未能实施的解决方案来表达您想要什么。

标签: javascript reactjs redux react-redux


【解决方案1】:

只需分配属性,它就会覆盖旧的。

export default function(state = initialState, action) {
  switch (action.type) {
    case GET_BOOKS:
      console.log(action.payload.results);
      // spread current state and inaddition to that set new books data
      // which overwrites books property from old state
      return { ...state, books : action.payload.results };
      // spread --^^^^^^^^^^^^^^^^^^^^^^^^^^^---
    default:
      return state;
  }
}

更新:如果您想将其与现有的连接,请执行以下操作。

export default function(state = initialState, action) {
  switch (action.type) {
    case GET_BOOKS:
      console.log(action.payload.results);
      return { ...state, books : [...state.books, ...action.payload.results] };
    default:
      return state;
  }
}

仅供参考:...state 部分用于复制其他状态属性(假设存在其他状态值)

【讨论】:

  • 我不能这样做,因为 api 是一个分页器,所以它返回更多结果但不会再次返回整个列表
  • 您需要在问题中提供更多信息
  • 假设有效载荷结果不在 books 数组中,您可以简单地将上面的 action.payload.books 替换为 [...action.payload.results, ...state.books]
  • @AlexBroadwin :我想你想连接,然后使用更新的解决方案
  • 问题是有效载荷的结果是一个对象数组,所以它只是使书籍成为数组内的对象数组
【解决方案2】:

你需要连接当前状态和来自 api 的数据

return {  books: [...state.books, ...action.payload.results] };

完整代码

import { GET_BOOKS } from "../actions/types";
const initialState = { books: [] };

export default (state: Object = initialState, action: Object) => {
  switch (action.type) {
    case GET_BOOKS:
      return { books: [...state.books, ...action.payload.results] };
    default:
      return state;
  }
};


【讨论】:

  • 问题是有效载荷的结果是一个对象数组,所以它只是使书籍成为数组内的对象数组
猜你喜欢
  • 2017-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-27
  • 2021-03-01
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多