【问题标题】:React State Rendering one step behind反应状态渲染落后一步
【发布时间】: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)
      }

【问题讨论】:

    标签: reactjs use-state


    【解决方案1】:

    想通了,我需要在 setHook 调用中使用扩展运算符

            setPDFStructure([...newElementOrder])
    

    这样做的原因是,如果仅更改数组的一部分,react 不会重新渲染

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-15
      • 2021-05-01
      • 2021-07-12
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      • 2021-11-20
      相关资源
      最近更新 更多