setState的触发问题

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吗?

阅读 1.5k
1 个回答
{
    //...,
    age: item.age + 1 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题