Synchronizing nested array within an object in useState hook

主宰稳场 提交于 2020-06-01 07:41:25

问题


I have defined a useState object as follow:

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:

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

The field "detailsOfPeople" that holds that array groupDetails shows nothing. But if I print "groupDetails" all values are shown. Within useEffect function I'm doing this:

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

回答1:


React State hooks are working async so you shouldn't wait state change after the setState call. You can catch the end of state change via useEffect.

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


来源:https://stackoverflow.com/questions/62062488/synchronizing-nested-array-within-an-object-in-usestate-hook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!