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

时间:2020-05-28 10:27:57

标签: javascript reactjs react-hooks react-functional-component

我已经定义了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]);

1 个答案:

答案 0 :(得分:2)

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

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