React update插件中 splice指令的理解

前端之家收集整理的这篇文章主要介绍了React update插件中 splice指令的理解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在看《React开发实战》一书中,其提到了React的update的指令,其可以对一个对象进行深度复制和修改,那为什么要update指令,因为我们知道,在javascript的世界中,对象是传的引用而不是值,当一个复杂的对象里面又嵌套了子对象的时候,如果把当前的对象做一个深度的复制,其实还是蛮复杂的,所以React中,其提供了一个帮助类库:update
其可以通过下面的方法进行安装:

npm install --save react-addons-update

其提供了下面的命令,具体可参看 @L_502_0@

  • $push: array
  • $unshift: array
  • $splice: array
  • $set: any
  • $merge: object
  • $apply: function

对其他的都很好理解,但是对splice命令,当时没有太理解。
比如,

let initialArray=[1,2,'a'];
let newArray=update(initialArray,{$splice:[[2,1,3,4]});

输出结果为: [1,2,3,4] ,那为什么是这个结果呢?
那么我来看看splice命令的格式,

Use .splice to remove item from array. Using delete,indexes of the array will not be altered but the value of specific index will be undefined,The splice() method changes the content of an array by removing existing elements and/or adding new elements.

Syntax: array.splice(start,deleteCount[,item1[,item2[,...]]])

let newArray=update(initialArray,{$splice:[[2,1,4]});

可以解释为,从第2个下标开始,删除一个元素,‘a’,然后把后面的3,4加入到后面。这样就成了 [1,4] 。

在看一个栗子,

let people = ["Bob","Sally","Jack"]
let toRemove = 'Bob';
let index = people.indexOf(toRemove);
people.splice(index,1);
console.log(people);
原文链接:https://www.f2er.com/react/302654.html

猜你在找的React相关文章