【问题标题】:Callback inside a useState updater function in react Hooksreact Hooks 中的 useState 更新器函数内的回调
【发布时间】:2020-12-12 20:06:36
【问题描述】:

我是 hook 新手,react 也是,我最近一直在看一些教程,我看到 Ben awad's video 用于动态表单,我尝试复制它。在那里,他在 useState 更新程序函数中使用了一个回调,这对我来说似乎是新的。他使用过的链接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;

【问题讨论】:

    标签: reactjs callback react-hooks


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-03
        • 2020-06-13
        • 1970-01-01
        • 1970-01-01
        • 2023-01-18
        • 1970-01-01
        • 2019-10-17
        • 2020-05-03
        相关资源
        最近更新 更多