[英]Strange behavior on state
我有一個帶有問題組件的表單,這個問題組件允許我添加問題的部分,如下圖所示:
同樣如您所見,我有一個按鈕可以刪除每個部分,這是我的部分組件上的按鈕:
<button
className="circle-button delete-section"
onClick={handleDeleteSection}
data-section-id={sectionId}
type="button"
>
×
</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"
>
×
</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.