react Hooks中useState updater函数内部的回调 [英] Callback inside a useState updater function in react Hooks

查看:109
本文介绍了react Hooks中useState updater函数内部的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,所以会做出反应,最近我一直在看一些教程,我看到了 Benawad的视频是动态表单,我尝试复制它.在那里,他在useState updater函数内部使用了一个回调,这对我来说似乎是新的.他使用了链接 setPeople(currentPeople => {})自变量 currentPeople 的含义是什么,为什么使用它,有人可以解释一下,谢谢!

Im new to hook and so is react,Ive been watching some tutorials lately,I saw Ben awad's video for dynamic forms and I tried replicating it.There he used a callback inside the useState updater function which seems new to me.He used link setPeople(currentPeople => {}) What is the argument currentPeople come from and why its used,Can you someone please explain,Thanks in advance!

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;

推荐答案

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

No better explanation than the official one. Here is the 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 [] 例如:您可能只发送一个要添加到人员阵列中的人员,因此最终只能将该人员附加到现有的人员阵列中.当然可以使用 setPeople([... people,newPerson]),但这在100%的地方是不正确的,因为 people 可能没有最新值,因此回调函数可以解救.

Your currentPeople is what the variable name suggests, the current value of the const [people, setPeople] = useState<Person[] For example: You might send only one person that you want to add to your people's array, so you end up just attaching that Person to an already existing array of Persons. Sure you could use setPeople([...people, newPerson]) but this wouldn't be correct in 100% of places because people might not have the latest value so the callback function comes to the rescue.

这篇关于react Hooks中useState updater函数内部的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆