在 React Hooks 的 useState updater 函数中回调

Callback inside a useState updater function in react Hooks

我是 Hook 的新手,也是 React 的新手,我最近看了一些教程,我看到了 Ben awad's video 的动态表单,我尝试复制 it.There 他在 useState 更新程序函数中使用了一个回调me.He 似乎是新手,用过 link setPeople(currentPeople => {}) 参数 currentPeople 的来源是什么以及为什么使用它,有人能解释一下吗,在此先感谢!

import { useState } from "react";
import "./App.css";
import { generate } from "shortid";
interface Person {
  id: string;
  firstName: string;
  lastName: string;
}
function App() {
  const [people, setPeople] = useState<Person[]>([
    {
      id: "5",
      firstName: "Aashiq",
      lastName: "Ahmed",
    },
  ]);
  return (
    <>
      <h2 style={{ textAlign: "center" }}>Dynamic Form </h2>
      <div style={{ textAlign: "center" }}>
        <button
          onClick={() => {
            setPeople((currentPeople) => [
              ...currentPeople,
              {
                id: generate(),
                firstName: "",
                lastName: "",
              },
            ]);
          }}
        >
          add new person
        </button>
        {people.map((p, index) => {
          return (
            <div key={p.id}>
              <input
                placeholder="first name"
                value={p.firstName}
                onChange={(e) => {
                  const firstName = e.target.value;
                  setPeople((
                    currentPeople 
                  ) =>
                    currentPeople.map((x) =>
                      x.id === p.id ? { ...x, firstName } : x
                    )
                  );
                }}
              />
              <input
                placeholder="last name"
                value={p.lastName}
                onChange={(e) => {
                  const lastName = e.target.value;
                  setPeople((currentPeople) =>
                    currentPeople.map((x) =>
                      x.id === p.id ? { ...x,lastName } : x
                    )
                  );
                }}
              />
            <button onClick={()=> setPeople( currentPeople =>currentPeople.filter(x=> x.id !== p.id) )}>x</button>
            </div>
          );
        })}
        <div>
          
          <pre>{JSON.stringify(people,  null,  3)}</pre>
        
        </div>
      </div>
    </>
  );
}

export default App;

没有比官方更好的解释了。 这是link:https://reactjs.org/docs/hooks-reference.html#usestate

setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

你的currentPeople就是变量名所暗示的,当前值 const [people, setPeople] = useState<Person[] 例如: 你可能只发送一个你想添加到你的人员数组的人,所以你最终只是将该 Person 附加到一个已经存在的 Persons 数组中。 当然你可以使用 setPeople([...people, newPerson]) 但这在 100% 的地方都是不正确的,因为 people 可能没有最新的值所以回调函数来拯救。

它是那个状态的当前值,当你想用前一个状态计算下一个状态时,这可能会派上用场。一个例子是切换功能,它将切换模态或某事。

const [isOpen, setIsOpen] = useState(false);
const toggleIsOpen = () => setIsOpen(open=>!isOpen);