在Redux reducer

时间:2018-02-12 18:57:39

标签: javascript redux

const state = [
  {10: {a: 22, b: 33}},
  {12: {a: 20, b: 33}},
  {15: {a: 22, b: 34}},
  {5: {a: 21, b: 30}},
  {9: {a: 29, b: 33}},
]

State是一个像上面这样的对象数组。当应用程序更新对象时,对象应该向上流动到第一个位置。

E.g。假设我们使用上面的第二个对象(使用主键12),然后复制并更新它,使它看起来像这样:

{12: {a: 45, b: 33}}

现在我们想将它插入到数组中,结果如下:

const state = [
  {12: {a: 45, b: 33}},
  {10: {a: 22, b: 33}},
  {15: {a: 22, b: 34}},
  {5: {a: 21, b: 30}},
  {9: {a: 29, b: 33}},
]

我理解如何以不可变的方式更新对象,但我无法理解如何完成上述操作。

2 个答案:

答案 0 :(得分:1)

或许这样的事情?



const state = [
  {10: {a: 22, b: 33}},
  {12: {a: 20, b: 33}},
  {15: {a: 22, b: 34}},
  {5: {a: 21, b: 30}},
  {9: {a: 29, b: 33}},
]


// find the numerical index of the object with the specified "key"
function findIndexOfKey(array, key){
  return array.findIndex(function(el){return key in el});
}


// modify object and move to front
function editObjectAndMoveToFront(array, key, updatedValues){
  // find index of object with key, for use in splicing
  var index = findIndexOfKey(array, key);

  // create the updated version of the specified object
  var originalObject = array[index];
  var originalObjectValue = originalObject[key];
  var editedObject = {};
  editedObject[key] =  Object.assign({}, originalObjectValue, updatedValues)

  // here is the new state, with the updated object at the front
  var newArray = [
    editedObject,
    ...array.slice(0, index),
    ...array.slice(index + 1)
  ]
  return newArray
}


const newState = editObjectAndMoveToFront(state, 12, {a: 45, b: 33})
console.log(newState);




答案 1 :(得分:1)

您可以使用类似

的内容
// an update function, here it just adds a new key
// to the object
const update = (x) => ({
  ...x,
  hello: "world"
});

// a filter factory
const withId = (id) => (item) => Boolean(item[id]); // item with specific ids
const withoutId = (id) => (item) => !Boolean(item[id]); // others

const state = [
  {10: {a: 22, b: 33}},
  {12: {a: 20, b: 33}},
  {15: {a: 22, b: 34}},
  {5: {a: 21, b: 30}},
  {9: {a: 29, b: 33}},
];

const id = 5;
const newState = state
  .filter(withId(id))
  .map(update)
  .concat(state.filter(withoutId(id)));


console.log(JSON.stringify(newState, null, 4));

这样做是为了过滤您想要更新的项目与其余项目之间的状态,将更新应用于选择并将未触及的项目连接到它们。

下面的另一个示例使用相同的想法说明您可以对多个项目执行更新:

const markAsDone = (todo) => ({
  ...todo,
  done: true
});
const isInGroup = (group) => (todo) => todo.group === group;
const not = (predicate) => (x) => !predicate(x);

const isWork = isInGroup("work");
const notWork = not(isWork);

const state = [
  {
    todo: "go shopping",
    group: "life"
  },
  {
    todo: "go work",
    group: "work",
  },
  {
    todo: "go sleep",
    group: "life"
  }
];

// get work related todos, mark as done and 
// append to todo list
const newState = state
  .filter(notWork)
  .concat(state
    .filter(isWork)
    .map(markAsDone));


console.log(JSON.stringify(newState, null, 4));