redux - React Redux 重命名 API 响应中的嵌套对象

标签 redux react-redux

我收到来自 API 的响应,并且在将操作发送到 reducer 之前,我尝试重命名操作中对象数组的嵌套对象属性。响应通常如下所示:

[
  {
    attributes: {
      name: "Item 1",
      price_cents: 1500
    }
  },
  {
    attributes: {
      name: "Item 2",
      price_cents: 1000
    }
  },
  ...
]

我想将 price_cents 更改为 price。在将其用作 reducer 的有效负载之前,如何更改它?

最佳答案

您可以使用Array#map遍历响应数组中的每个值,并使用所需的属性和名称创建一个新对象:

const actionCreator = (response) => ({
  type: 'ACTION_TYPE',
  payload: response.map((item) => ({
    attributes: {
      name: item.attributes.name,
      price: item.attributes.price_cents
    }
  })
});

关于redux - React Redux 重命名 API 响应中的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41914631/

相关文章:

javascript - 如何更新 reducer 中对象的 1 个属性?

cors - 调用axios.get时发生CORS错误

javascript - 如何在 React/Redux 应用程序中刷新页面后保持登录状态

javascript - 检测 redux 存储更改

reactjs - react : Is it bad practice to import a child component directly rather than pass in as a dependency?

javascript - 在 Redux 中将多个操作传递给 mapDispatchToProps

javascript - 拦截 switch default 或 case 中抛出的错误时的不同行为(React/Redux)

javascript - 无法使用 reducer 中的条件语句更改处于状态的数组的第二个值 --- Redux

node.js - 缺少 A 的类型注释。A 是在函数类型中声明的类型参数

javascript - 删除嵌套数组中对象键的有效方法