简体   繁体   English

如何使用 Reducer 中的数组更新多个值

[英]How to update multiple values with an array inside Reducer

I have the following code to update the currentScore of a rubricItem object. This works fine.我有以下代码来更新rubricItem object 的currentScore 。这工作正常。

case SAVE_SCORELIST_SUCCESS:
    const scoreItem = action.payload.scoreItem;
    return {
        ...state,
        loading: false,
        editing: false,
        rubricItems: {
            ...state.rubricItems,
            [scoreItem.rubricItemId]: {
                ...state.rubricItems[scoreItem.rubricItemId],
                currentScore: scoreItem.currentScore,
            }
        }
    };

However, I may receive an array object holding scores for multiple rubricItems instead of updating a single rubricItem with a single scorItem as I did above.但是,我可能会收到一个数组 object,其中包含多个rubricItems的分数,而不是像上面那样用单个scorItem更新单个rubricItem

I know I can use .map() to iterate through the array:我知道我可以使用.map()遍历数组:

scoreItems.map(si=>{})

But, I do not know how I can integrate it into this:但是,我不知道如何将它整合到这个中:

case SAVE_SCORELIST_SUCCESS:
    const scoreItems = action.payload.scoreItems;

    return {
        ...state,
        loading: false,
        editing: false,
        rubricItems: {
            ...state.rubricItems,
            [scoreItems[x].rubricItemId]: {
                ...state.rubricItems[scoreItems[x].rubricItemId],
                currentScore: scoreItems[x].currentScore,
            }
        }
    };

Any ideas?有任何想法吗?

You can try this:你可以试试这个:

First you need to iterate over scoreItems and make a map object of updated score items.首先,您需要迭代 scoreItems 并生成map object 的更新分数项目。

Once you have done that, you can use the spread operator with the current score items in state.完成后,您可以对 state 中的当前得分项使用spread运算符。

case SAVE_SCORELIST_SUCCESS:
let updatedScoreItems = {};
action.payload.scoreItem.forEach(scoreitem => {
  updatedScoreItems[scoreItem.rubricItemId] = {
    ...state.rubricItems[scoreItem.rubricItemId],
    currentScore: scoreItem.currentScore,
  }
})
return {
  ...state,
  loading: false,
  editing: false,
  rubricItems: {
    ...state.rubricItems,
    ...updatedScoreItems
  }
};

Instead of mapping over scoreItem , map over the rubricItems which will be cleaner. map 不是映射到scoreItem上,而是映射到rubricItems上,这样会更干净。

const updatedRubricItems = items.rubricItems.map(rubricItem => {
    const scoreForRubric = scoreItems.find(si => si.rubricItemId === rubricItem.id);// i assume you have some id for your rubric item
    if(scoreForRubric){
        return {...rubricItem, currentScore: scoreForRubric.currentScore}
    }else {
        return rubricItem
    }
});

return {
  ...state,
  loading: false,
  editing: false,
  rubricItems: updatedRubricItems
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM