通过特定索引将数组更改为对象来更新反应状态

Updating Reactive state by specific index changes array to object

我的状态是这样的结构:

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

在我的 reducer 中,我试图通过索引访问 book 数组并将其 pages 数组替换为新数组。我在 google chrome 值变化前后观察 Redux 值。 它将整个数组转换为 object.Before redux 中的 'book' 数组看起来像:

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

更改后:

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

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

这是我的减速器中的代码:

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[]
          }
        }
    };
}

你能试试看是否有效吗?

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
        }))
    };
}

@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 项目。