繁体   English   中英

状态上的奇怪行为

[英]Strange behavior on state

我有一个带有问题组件的表单,这个问题组件允许我添加问题的部分,如下图所示:

在此处输入图片说明

同样如您所见,我有一个按钮可以删除每个部分,这是我的部分组件上的按钮:

<button
    className="circle-button delete-section"
    onClick={handleDeleteSection}
    data-section-id={sectionId}
    type="button"
  >
    &times;
  </button>

这个按钮有一个handleDeleteSection ,这个方法在父组件上,下面是方法:

const handleDeleteSection = (event) => {
    const idToDelete = event.target.dataset.sectionId;
    const updatedSections = questionaryState.sections.filter(
      (section) => section.sectionId !== idToDelete
    );
    // update the state with new sections
    setQuestionaryState((questionaryState) => ({
      ...questionaryState,
      sections: updatedSections,
    }));
  };

但是updatedSections 的长度总是错误的例如:如果我点击“section 1”的删除按钮,updatedSections 长度为0 如果我点击“section 3”的删除按钮,如果我点击“section 3”的删除按钮,updatedSections 长度为2第 4 节'更新后的节长度为 3

但如下图所示, questionaryState.sections 有 4 个元素:

在此处输入图片说明

关于这里发生的事情的任何想法或建议,因为如果没有正确的部分数组,当用户按下删除按钮时我无法删除该部分

在此先感谢您的帮助

编辑:上传视频

这是一个带有示例的视频: https : //vimeo.com/469746051

您以错误的方式使用 setQuestionaryState (state) 钩子,您应该通过传递一个对象而不是使用回调函数在删除被点击的元素后更新状态:如下所示

const handleDeleteSection = (event) => {
    const idToDelete = event.target.dataset.sectionId;
    const updatedSections = questionaryState.sections.filter(
      (section) => section.sectionId !== idToDelete
    );

    // update the state with new sections
    setQuestionaryState({
      ...questionaryState,
      sections: updatedSections,
    });
};

您需要在过滤之前传播您的状态,以防止在创建新数组时更安全地传递 ref,然后将过滤后的结果直接传递给处于设置状态的“部分”

const handleDeleteSection = (event) => {
    const idToDelete = event.target.dataset.sectionId;
    const sectonsTemp =  [...questionaryState.sections]
    const updatedSections =sectonsTemp.filter(
      (section) => section.sectionId !== idToDelete
    );
    // update the state with new sections
   setQuestionaryState({
      ...questionaryState,
      sections: updatedSections ,
    });

  };

这对我有用。

const handleDeleteSection = (idToDelete) => {
  const updatedSections = questionaryState.sections.filter(
    (section) => section.sectionId !== idToDelete
  );

  setQuestionaryState({
    sections: updatedSections
  });
};

HTML

<button
  className="circle-button delete-section"
  onClick={() => handleDeleteSection(sectionId)}
  type="button"
>
  &times;
</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM