[Redux] Avoiding Object Mutations with Object.assign() and ...spread

Learn how to use Object.assign() and the spread operator proposed for ES7 to avoid mutating objects.

 

/*
 * Open the console to see
 * that the tests have passed.
 */

const toggleTodo = (todo) => {
  return {
    ...todo,
    completed: !todo.completed
  };
};

const testToggleTodo = () => {
  const todoBefore = {
    id: 0,
    text: 'Learn Redux',
    completed: false
  };
  const todoAfter = {
    id: 0,
    text: 'Learn Redux',
    completed: true
  };
  
  deepFreeze(todoBefore);
  
  expect(
    toggleTodo(todoBefore)
  ).toEqual(todoAfter);
};

testToggleTodo();
console.log('All tests passed.');

Here '...todo', spread object, whcih is not available in ES6, but will be in ES7, It is fairly popular, and it is enabled in Babel if you use the stage two preset.

https://babeljs.io/docs/plugins/preset-stage-2/

posted @ 2015-11-30 03:31  Zhentiw  阅读(326)  评论(0编辑  收藏  举报