map()转换数组
如果要更改数组的部分或全部项目,可以使用 map() 创建新数组。你将传递给 map 的函数可以根据其数据或索引(或两者)决定如何处理每个条目。
const [shapes, setShapes] = useState(
initialShapes
);
function handleClick() {
const nextShapes = shapes.map(shape => {
if (shape.type === 'square') {
// No change
return shape;
} else {
// Return a new circle 50px below
return {
...shape,
y: shape.y + 50,
};
}
});
// Re-render with the new array
setShapes(nextShapes);
}
slice()插入到数组
let nextId = 3;
const initialArtists = [
{ id: 0, name: 'Marta Colvin Andrade' },
{ id: 1, name: 'Lamidi Olonade Fakeye'},
{ id: 2, name: 'Louise Nevelson'},
];
const [name, setName] = useState('');
const [artists, setArtists] = useState(
initialArtists
);
function handleClick() {
const insertAt = 1; // Could be any index
const nextArtists = [
// Items before the insertion point:
...artists.slice(0, insertAt),
// New item:
{ id: nextId++, name: name },
// Items after the insertion point:
...artists.slice(insertAt)
];
setArtists(nextArtists);
setName('');
}
reverse() 和 sort()反转或排序
对数组进行反转或排序。JavaScript reverse() 和 sort() 方法正在改变原始数组,因此在React中不能直接使用。但是,可以先复制数组,然后再对其进行更改
const initialList = [
{ id: 0, title: 'Big Bellies' },
{ id: 1, title: 'Lunar Landscape' },
{ id: 2, title: 'Terracotta Army' },
];
const [list, setList] = useState(initialList);
function handleClick() {
const nextList = [...list];
nextList.reverse();
setList(nextList);
}
使用 [...list] 扩展语法创建原始数组的副本,然后就可以使用 reverse() 和 sort()
复制数组,也无法直接改变其中的现有项。这是因为复制是浅层的[...list]语法属于浅层复制 - 新数组将包含与原始数组相同的项目。因此,如果你修改复制数组中的对象,就会改变现有状态。这个就是状态突变。
#使用 Immer 编写简洁的更新逻辑
改变了 Immer 提供的特殊 draft 对象。同样,你可以将 push() 和 pop() 等修改方法应用于 draft 的内容。