`newArray = myArray`和`newArray = [... myArray]`之间有什么区别?

时间:2019-06-15 11:57:00

标签: javascript redux state

在一些Freecodecamp redux挑战中,我遇到了一个教状态不变性的挑战。而且我应该“从追加到最后的动作属性action.todo返回带有该项目的新数组”。

const ADD_TO_DO = 'ADD_TO_DO'; //Type of action

// A list of strings representing tasks to do:
const todos = [
  'Go to the store',
  'Clean the house',
  'Cook dinner',
  'Learn to code',
];
// an example todo argument would be 'Learn React',
//Action creator
const addToDo = (todo) => {
  return {
    type: ADD_TO_DO,
    todo
  }

}

1:我尝试过:返回错误:Cannot add property 4, object is not extensible

const immutableReducer = (state = todos, action) => {
  switch(action.type) {
    case ADD_TO_DO:
      let newState = state;
      newState.push(action.todo);
      return newState;
    default:
      return state;
  }
};

2:这是可行的

const immutableReducer = (state = todos, action) => {
  switch(action.type) {
    case ADD_TO_DO:
      return [...state, action.todo];
    default:
      return state;
  }
}; 

将状态数组分配给newState会传递数组元素以外的其他属性吗? 状态数组与普通数组有何不同?

在此先感谢您,如果有重复的代码,请原谅我。

0 个答案:

没有答案