更新 NGRX/Redux 存储中数组中对象的属性不起作用

jam*_*nde 0 javascript reactjs redux ngrx angular

在我的 Reducer 中,我试图更新字典集合中保存的数组中对象的属性,但它不起作用,我不知道为什么。我的状态的 results 属性是一个键/值对的字典,值是一个数组。

我尝试使用 map 函数创建一个新数组,但我的结果和状态没有更新。这是我的代码:

 case LOAD_SUCCESS: {
      const form = (action as LoadSuccessAction).form;

      return {
         results: {
           ...state.results,
           ...state.results['FORMS'].map(item => 
             item.id === form .id
              ? {...item, 'categories': form.categories}
              : item)           
         },    
        loading: false,
        loaded: true
      };
    } 
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

gsc*_*gsc 6

这里:

...state.results['FORMS'].map(…),
Run Code Online (Sandbox Code Playgroud)

您正在将更新项的数组(updated FORMS) 与 state 的results属性(包含的对象FORMS)合并。

如果项目的类别和 ID 是数字,则最终结果将如下所示(仅显示results):

{
    '0': { categories: 15, id: 10 },
    '1': { categories: 7, id: 11 },
    FORMS: [ /* its original content before the update */ ],
}
Run Code Online (Sandbox Code Playgroud)

相反,您应该将新状态的FORMS属性设置为更新后的数组:

return {
    // loaded, loading…
    results: {
        ...state.results,
        FORMS: state.results.FORMS.map(
            item => item.id === form.id ? {
                ...item,
                categories: form.categories,
            } : item,
        ),
    },
}
Run Code Online (Sandbox Code Playgroud)