Javascript 如何更新Redux中的状态-向上和向下移动-反应

Javascript 如何更新Redux中的状态-向上和向下移动-反应,javascript,reactjs,redux,Javascript,Reactjs,Redux,我试图找出如何更新redux中的状态,以便在单击时上下移动元素 state是一个对象数组,当前有3个元素,分别为id、text和isCrossed:false。单击时,我正在传递id,因此action.id将是我要移动的元素的id 下面是我的当前代码,但它不起作用。它似乎只移动一次,然后代码就断了。我添加了if语句以避免向上移动第一个元素 case 'UP_TODO': { return state.map((todo, idx, arr) => { if (ac

我试图找出如何更新redux中的状态,以便在单击时上下移动元素

state是一个对象数组,当前有3个元素,分别为id、text和isCrossed:false。单击时,我正在传递id,因此action.id将是我要移动的元素的id

下面是我的当前代码,但它不起作用。它似乎只移动一次,然后代码就断了。我添加了if语句以避免向上移动第一个元素

case 'UP_TODO': {
     return state.map((todo, idx, arr) => {
        if (action !== arr[0]) {
          return (todo.id === action.id  ? arr[idx - 1] : todo.id === action.id - 1 ? arr[idx + 1] : todo)
        } else {
          return todo
        }
      });
      
    }

无法对当前映射到的数组进行变异。首先需要浅层复制数组,然后交换指定索引处的值

case 'UP_TODO': {
  // compute todo index
  const index = state.findIndex(todo => todo.id === action.id);

  // if todo index is found and not first element,
  // and todos array has length 2 or more
  if (index > 0 && state.length > 1) {
    // shallow copy state
    const newState = [...state];

    // swap values at found index and index - 1
    [newState[index], newState[index - 1]] = [newState[index - 1], newState[index]];

    return newState;
  } else {
    // not swappable, return current state
    return state;
  }
}

同样,对于下移情况,您需要确保数组中至少有2个元素,并且找到的索引不是todos数组中的最后一个元素。

我希望此方法可以帮助您创建新数组:

function moveArrayItemToNewIndex(arr, old_index, new_index) {
    if (new_index >= arr.length) {
        var k = new_index - arr.length + 1;
        while (k--) {
            arr.push(undefined);
        }
    }
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
    return arr; 
};