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

时间:2018-03-04 13:47:36

标签: arrays react-native redux immutability reducers

我目前正在导入此库:

import update from 'react-addons-update';

这是我的清单:

  

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

我的行动:

  

action.type:'change_title'   
  action.payload:[2,“一些新标题”]

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

这是我的reducer代码:

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

正如你所看到的,在它的当前状态下,我的reducer函数总是改变了第一个数组中的“title”值,但我想知道:怎么能我根据“id”值指定要修改的数组?

1 个答案:

答案 0 :(得分:1)

你至少可以通过两种方式来做到这一点。首先,使用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]
        };
    });    
相关问题