为什么子状态值在父回调函数中第一次不更新?我想根据状态禁用输入字段。
带有完整示例的沙盒:https://z3wu6.csb.app/
答案 0 :(得分:1)
PageHeader
初始状态为true
,当您单击按钮时,将调用editViewHandler
。它会切换 此 组件的edit
状态,然后使用 current < / em>值editCallback
,最初是edit
。您正在将未更新的值发送给回调! (您在true
中再次将其设置为true
。也可以通过反转发送给UserProfile
的{{1}}值来解决此问题。
edit
我看到您还在editCallback
中复制了此const [edit, setEditView] = useState(true);
const editViewHandler = () => {
setEditView(!edit);
editCallback(!edit); // <-- send the same value you update state to
};
状态。您不应该重复状态。您想要一个单一的真理来源。
您已经从edit
传递了UserProfile
,因此只需将那个附加为按钮的回调。
在editCallback
的源回调中切换值
UserProfile
并附加到按钮的UserProfile
处理程序
const UserProfile = () => {
const [edit, setEdit] = useState(true);
const editCallback = () => setEdit(edit => !edit);
return (
<>
<PageHeader
button
editCallback={editCallback}
title="User Profile"
subtitle="Overview"
/>
<UserAccountDetails edit={edit} />
</>
);
};