最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Updating property of object in array in NGRXRedux store not working - Stack Overflow

programmeradmin6浏览0评论

In my Reducer, I'm trying to update the property of an object in an array held within a dictionary collection, but it's not working and I can't figure out why. The results property of my state is a dictionary of key/value pairs, and the value is an array.

I tried to use the map function to create a new array but my results and state does not update. This is my code:

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

What am I doing wrong?

In my Reducer, I'm trying to update the property of an object in an array held within a dictionary collection, but it's not working and I can't figure out why. The results property of my state is a dictionary of key/value pairs, and the value is an array.

I tried to use the map function to create a new array but my results and state does not update. This is my code:

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

What am I doing wrong?

Share Improve this question edited Oct 23, 2018 at 17:46 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked May 16, 2018 at 2:46 james Makindejames Makinde 9933 gold badges18 silver badges37 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Here:

...state.results['FORMS'].map(…),

you’re merging the array of updated items (updated FORMS) with state’s results property (the object containing FORMS).

If item’s categories and ids were numbers, the end result would look like this (only showing results):

{
    '0': { categories: 15, id: 10 },
    '1': { categories: 7, id: 11 },
    FORMS: [ /* its original content before the update */ ],
}

Instead, you should set new state’s FORMS property to your updated array:

return {
    // loaded, loading…
    results: {
        ...state.results,
        FORMS: state.results.FORMS.map(
            item => item.id === form.id ? {
                ...item,
                categories: form.categories,
            } : item,
        ),
    },
}
发布评论

评论列表(0)

  1. 暂无评论