react组件的更新机制只对数组进行的一个浅对比,也就是说没有改变它的引用地址,所以我们要改变数组时应该进行一次拷贝。

当数组和对象只有一级时,展开运算符和一些库函数复制方法都是深拷贝

1
2
const arrCopy = arr.slice();
const objCopy = Object.assign({},obj)

数组中使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import React, { useEffect, useState } from 'react';

const App = () => {
const [arr, setArr] = useState([1, 2, 3]);
const [value, setValue] = useState();
const change = () => {
// setArr((pre) => {
// if (pre.length == 0) return [];
// pre[0] = 100;
// let newArr = pre.slice();
// return newArr;
// })
arr[0] = 100;
let newArr = arr.slice();
setArr(newArr);
}
const deleteItem = (index) => {
setArr((pre) => {
pre.splice(index, 1);
let newArr = pre.slice();
return newArr;
})
console.log(arr);
}
const addItem = (num) => {
let inputDom = document.getElementById('inputId');
setArr((pre) => {
pre.push(inputDom.value);
let newArr = pre.slice();
return newArr;
})
console.log(arr);
}
let arr1 = [1, 2, 3, 4];
let arr2 = arr1.slice();
arr2.splice(0, 1);
console.log(arr1, arr2);// 可以发现修改拷贝之后的arr2并不影响arr1
return (
<div>
<button onClick={change}>change</button>
<input value={value} id='inputId'></input>
<button onClick={() => addItem(value)}>add</button>
<div>
{
arr.map((item, index) => {
return (
<div>{item}{index} <button onClick={() => deleteItem(index)}>delete</button></div>
)
})
}
</div>
</div>
)
};

export default App;

对象中使用

1
2
3
4
5
6
7
8
const [obj,setObj]=useState({
name:'xiaowang'
age:'10';
});

// 更新值
let newObj = {...obj,age='18'}
setObj(newObj);