React Native:指定要在 reducer 中修改的数组项(使用 React Immutability helpers)

React Native: Specify which array item to modify in reducer (using React Immutability helpers)

我目前正在导入这个库:

import update from 'react-addons-update';

这是我的清单:

[{id: 1, title: "some title"}, {id: 2, title: "some other title"}]

而我的行动:

action.type: 'change_title'
action.payload: [2, "some new title"]

action.payload中的第一个参数指的是我要更改的数组的id

这是我的减速器代码:

export default (state = [], action) => {
  switch (action.type) {
    case 'change_title':
      return update(state, {
        0: {
          title: { $set: action.payload[1] }
        }
      });
    default:
      return state;
  }
};

如您所见,在当前状态下,我的 reducer 函数 always 更改 第一个数组 中的 "title" 值,但我想知道:如何根据 "id" 值指定要修改的数组?

我认为你至少可以通过两种方式做到这一点。首先,使用 update(),您需要使用 Array.prototype.findIndex():

找到要更新的项目的索引
const index = state.findIndex(x => x.id === action.payload[0]);

case 'change_title':
  return update(state, {
    [index]: {
      title: { $set: action.payload[1] }
    }
  });

或者只使用地图:

case 'change_title':
    return state.map(item ==> {
        if(item.id !== action.payload[0]) {
            return item;
        }

        return {
            ...item,
            title: action.payload[1]
        };
    });