在 useState 钩子中同步对象内的嵌套数组

Synchronizing nested array within an object in useState hook

我定义了一个 useState 对象如下:

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

我已经完成填充嵌套数组 groupDetails,但是当我这样做时:

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

保存数组 groupDetails 的字段 "detailsOfPeople" 不显示任何内容。但是如果我打印 "groupDetails" 所有值都会显示。 在 useEffect 函数中我这样做:

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

React 状态挂钩正在异步工作,因此您不应在调用 setState 后等待状态更改。您可以通过 useEffect 捕获状态更改的结束。

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