简体   繁体   English

在 useState 挂钩中同步 object 中的嵌套数组

[英]Synchronizing nested array within an object in useState hook

I have defined a useState object as follow:我已经定义了一个 useState object 如下:

const [groupDetails, setGroupDetails] = React.useState([
    { fullName: "", phoneNo: "", gender: "" },
  ]);
  const [state, setState] = React.useState({
    fullName: "",
    phoneNo: " ",
    email: "",
    gender: "",
    idProof: "",
    noOfPeople: "",
    bookingId: "",
    detailsOfPeople: groupDetails,
  });

I have done populating the nested array groupDetails , but when I do:我已经完成了嵌套数组groupDetails的填充,但是当我这样做时:

console.log("state object:",state);

The field "detailsOfPeople" that holds that array groupDetails shows nothing.包含数组groupDetails的字段“detailsOfPeople”什么也不显示。 But if I print "groupDetails" all values are shown.但是,如果我打印“groupDetails”,则会显示所有值。 Within useEffect function I'm doing this:在 useEffect function 我这样做:

useEffect(() => {
    setGroupDetails(groupDetails);
    setState(state);
  }, [state, groupDetails]);

React State hooks are working async so you shouldn't wait state change after the setState call. React State 钩子正在异步工作,因此您不应在 setState 调用后等待 state 更改。 You can catch the end of state change via useEffect.您可以通过 useEffect 捕获 state 更改的结尾。

useEffect(() => {
    setGroupDetails(groupDetails);
    setState(prevState => ({...prevState, detailsOfPeople: groupDetails}) );
}, [groupDetails]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM