export default function Friend() {
const [friends, setFriends] = useState([
{ id: 1, name: "feeco", age: 18 },
{ id: 2, name: "hello", age: 19 },
{ id: 3, name: "world", age: 20 },
])
function addOne(id) {
const newFriends = friends.map((item) => {
if (item.id === id) return { ...item, age: age + 1 }
return item
})
setFriends(newFriends)
}
return (
<div>
<ul>
{friends.map((friend) => {
return (
<li key={friend.id}>
{friend.name}==={friend.age}
</li>
)
})}
</ul>
<button onClick={() => {addOne(1)}}>
每次点我,第一个人的年龄+1
</button>
</div>
)
}
以上这个代码,只有点击第一次的时候好用,就是18岁变成19岁,后边无论点击多少次第一个人的年龄都会停留在19岁,是我对于useState的理解有什么问题吗?map不是每次返回新的数组,替换本来的friends吗?