问题
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