为什么子状态值不会在父回调函数中第一次更新?

时间:2020-07-11 06:11:12

标签: reactjs react-hooks

为什么子状态值在父回调函数中第一次不更新?我想根据状态禁用输入字段。

带有完整示例的沙盒:https://z3wu6.csb.app/

1 个答案:

答案 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} />
    </>
  );
};

Edit stoic-night-puu8m