【问题标题】:Updating Reactive state by specific index changes array to object通过特定索引更新反应状态将数组更改为对象
【发布时间】:2019-05-17 22:18:56
【问题描述】:

我的状态有这样的结构:

state
  books {}  <-- object
    book    <-- array
      pages <-- array

在我的 reducer 中,我试图通过索引访问 book 数组并用新的 pages 数组替换它的 pages 数组。我在值更改之前和之后在我的谷歌浏览器中观察 Redux 值。 它将整个数组转换为一个对象。在 redux 中的 'book' 数组之前看起来像:

book: [{...}, {...}, {...}]

改动后:

book: {{0: {...}, 1: {...}, 2: {...}}

如何在 redux 中保持我的 book 对象的原始显示?

这是我的 reducer 中的代码:

export interface MyState {
  book: BookItem[];
  pages: Pages[];
}

function updatePages(index: number, state: MyState)  {
    // set up my new pages array here into newPages variable
    return {
        ...state,
        book: {
          ...state.book,
          [index]: {
            ...state.book[index],
            pages: newPages as Pages[]
          }
        }
    };
}

【问题讨论】:

  • 请发布更改前后的数据示例 - 特别是您希望数据在更改后的样子。目前尚不清楚您希望数据看起来如何。看看你的reducer,很明显为什么你会得到这个结构{{0: {...}, 1: {...}, 2: {...}}

标签: reactjs typescript redux store


【解决方案1】:

你可以试试这个,看看它是否有效?

function updatePages(index: number, state: MyState)  {
    // set up my new pages array here into newPages variable
    return {
        ...state,
        book: state.book.map(bk => ({
            ...bk,
            pages: newPages as Pages[]
        }))
    };
}

编辑

function updatePages(index: number, state: MyState)  {
    // set up my new pages array here into newPages variable
    return {
        ...state,
        book: state.book.map((bk, idx) => ({
            ...bk,
            pages: idx === index ? newPages as Pages[] : bk.pages
        }))
    };
}

【讨论】:

  • 谢谢加布里埃尔,但是我要更改的索引的引用在哪里?我不想更改数组中的所有项目
【解决方案2】:

@Gabriel Ferrarini 的回答解决了您的问题,这就是我支持它的原因。但是,作为映射的替代方案,我想提供一个不同的答案。由于那里有当前索引,您可以使用Object.assign 来操作book 的页面。

function updatePages(index: number, state: MyState) {
  // newPages setup...
  return {
    ...state,
    book: Object.assign([], state.book, {
      [index]: { ...state.book[index], pages: newPages as Pages[] }
    })
  };
}

我们在这里使用Object.assign 来操作带有索引的数组。同样,在不改变原始状态(使用扩展语法)的情况下,我们只是将我们的页面分配为 newPages 用于 book 项目。

【讨论】:

  • 是的,确实如此 :) 您不会经常看到这种方法。大多数时候使用mapfilter 方法是可行的方法。但是,如果你有一个像这里一样的索引而不映射整个数组,你可以这样做。
猜你喜欢
  • 2020-03-12
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2021-12-26
  • 2018-03-21
  • 2020-07-02
  • 1970-01-01
  • 2017-08-08
相关资源
最近更新 更多