跳至主要内容

React State 陣列物件操作

React State 陣列物件操作

比較 Mutable Immutable 操作

  • mutable : 直接改既有 instance。
  • immutable : 回傳新建立的物件
Mutable Style
回傳成功數?非 Array
Immutable Style
新增push, unshift
回傳陣列長度
concat, [...arr] spread syntax
移除pop, shift, splice
回傳陣列最後,第一,被刪除的元素陣列
filter, slice
取代splice, arr[i] = ... assignmentmap
排序reverse, sort將既有 Array 先行複製
  • push : 陣列 末尾 添加一個或多個元素
  • pop : 移除並回傳陣列的 最後 一個元素
  • unshift : 陣列的 開頭 添加一個或多個元素。
  • shift : 移除並回傳陣列中的 第一 個元素
  • splice : 元素移除,並回傳 被刪除 元素的新陣列
  • reverse : in-place,原陣列反轉後的參考
  • sort : in-place,原陣列排序後的參考

Array 新增 Items

  • spread syntax 取代 push/unshift 的功能
import { useState } from 'react';

export default function List() {
let nextId = 0;
const [name, setName] = useState('');
const [artists, setArtists] = useState([]);

return (
<>
<h1>Inspiring sculptors:</h1>
<input
value={name}
onChange={e => setName(e.target.value)}
/>
<button onClick={() => {
setArtists([
...artists,
{ id: nextId++, name: name }
]);
}}>Add</button>
<ul>
{artists.map(artist => (
<li key={artist.id}>{artist.name}</li>
))}
</ul>
</>
);
}

移除

  • filter 取代刪除概念
import { useState } from 'react';

const [name, setName] = useState('');
const [nextId, setNextId] = useState(3);

let initialArtists = [
{ id: 0, name: 'Marta Colvin Andrade' },
{ id: 1, name: 'Lamidi Olonade Fakeye'},
{ id: 2, name: 'Louise Nevelson'},
];

const [artists, setArtists] = useState(initialArtists);

export default function List() {
const [artists, setArtists] = useState(
initialArtists
);

return (
<>
<h1>Remove:</h1>

<input
value={name}
onChange={e => setName(e.target.value)}
/>
<br/>
filter 直接 return new array,所以不像 spread operator 有外加一個 []
<button onClick={() => {
setArtists(
artists.filter(a =>
a.name !== name
)
);
}}>Remove</button>

<ul>
{artists.map(artist => (
<li key={artist.id}>
{artist.name}{' '}
<button onClick={() => {
setArtists(
artists.filter(a =>
a.id !== artist.id
)
);
}}>
Remove: filter
</button>
</li>
))}
</ul>
</>
);
}

元素修改

取代

排序