【发布时间】:2022-06-28 23:43:15
【问题描述】:
我有一个函数可以处理在页面上拖动元素并将该元素与目标元素交换(使用 onDragStart 和 onDrop)。该函数准确地获取用户在页面上的位置并相应地更新页面布局(对我的问题来说不是超级重要)。一切正常,除了渲染是一个动作。更奇怪的是,如果不理会它最终会在 10 秒左右后更新,但在再次尝试该操作后会立即更新。我相信在数组有机会更新之前调用了 useState 'set'。有什么建议吗?
// This function is called when the element is grabbed
const handleElementDrag = (index) => {
setDragElementID(index)
}
// This function is called when the element is dropped
const handleElementDrop = async (index, page, container, section) => {
// Sanity Check
console.log('dropped', dragElementID, 'onto', index, 'page:', page, 'container:', container, 'section:', section, ' - element level')
// Declare new array based on current page structure
const newElementOrder = PDFStructure;
// Swap array elements
[newElementOrder[page].contents[container].contents[section].contents[dragElementID], newElementOrder[page].contents[container].contents[section].contents[index]] = [newElementOrder[page].contents[container].contents[section].contents[index], newElementOrder[page].contents[container].contents[section].contents[dragElementID]]
// Update current layout
setPDFStructure(newElementOrder)
}
【问题讨论】: