我定义了一个useState对象,如下所示:
const [groupDetails, setGroupDetails] = React.useState([
{ fullName: "", phoneNo: "", gender: "" },
]);
const [state, setState] = React.useState({
fullName: "",
phoneNo: " ",
email: "",
gender: "",
idProof: "",
noOfPeople: "",
bookingId: "",
detailsOfPeople: groupDetails,
});
我已经完成了填充嵌套数组组的详细信息,但是当我这样做时:
console.log("state object:",state);
保存该数组组详细信息的字段"detailsOfPeople"不显示任何内容。但是如果我打印"组详细信息",则会显示所有值。 在useEffect函数中,我正在这样做:
useEffect(() => {
setGroupDetails(groupDetails);
setState(state);
}, [state, groupDetails]);
React State 钩子是异步工作的,所以你不应该在 setState 调用后等待状态更改。您可以通过 useEffect 捕获状态更改的结束。
useEffect(() => {
setGroupDetails(groupDetails);
setState(prevState => ({...prevState, detailsOfPeople: groupDetails}) );
}, [groupDetails]);