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

本文介绍如何利用Object.assign()方法及ES7中的扩展运算符来避免对象的直接修改,通过具体示例展示了如何使用这些特性来切换todo项的完成状态。

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/

转载于:https://www.cnblogs.com/Answer1215/p/5006162.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值