Diff算法3個(gè)策略
- 跨層級(jí)不進(jìn)行不比較
- 不同類不進(jìn)行比較
- 同類同級(jí)通過(guò)key比較
主要對(duì)第三種進(jìn)行解釋
例子
更新前組件:A-B-C-D => 更新后組件:C-B-E-A
滿足child._mountIndex < lastIndex才會(huì)進(jìn)行組件移動(dòng)
child._mountIndex其實(shí)是當(dāng)前的index,但此時(shí)正在比較,還未變動(dòng),也就是更新前的indexlastIndex是一個(gè)不斷更新的值,每一個(gè)組件比較后,lastIndex為Math.max(prevChild.mountIndex,lastIndex)
遍歷新集合:
比較C:child._mountIndex為2,lastIndex為0,不滿足,不執(zhí)行變動(dòng),更新lastIndex為2;
比較B:child._mountIndex為1,lastIndex為2,滿足,執(zhí)行移動(dòng),更新lastIndex為2;
比較E:舊集合未找到,執(zhí)行添加,lastIndex為2;
比較A:child._mountIndex為0,lastIndex為2,滿足,執(zhí)行移動(dòng),更新lastIndex為2;
遍歷舊集合,發(fā)現(xiàn)D,執(zhí)行刪除
缺點(diǎn)
從上面例子可以發(fā)現(xiàn),diff算法主要通過(guò)不斷更新lastIndex進(jìn)行判斷,因此,
如果lastIndex一開始就更新成最后一個(gè)index,那么后面的所有組件都要進(jìn)行變動(dòng)。
例如:
更新前組件:A-B-C-D => 更新后組件:D-A-B-C
一開始比較D:child._mountIndex為3,lastIndex為0,不滿足,不執(zhí)行變動(dòng),更新lastIndex為3;
此時(shí)lastIndex已經(jīng)為最大值,后面所有比較都會(huì)滿足child._mountIndex < lastIndex
更新變動(dòng)為:
D組件不變
A,B,C組件都要移動(dòng)