【问题标题】:How to remove element's ref after filtering it from the list从列表中过滤后如何删除元素的引用
【发布时间】:2020-10-24 04:30:45
【问题描述】:

我正在将“砖”对象的数组渲染为组件上的简单 div。 我还使用 useRef 保存砖块的所有 refs,当每个砖块元素都被保存时,它的 id 在“brickRefs”对象中。

在某些情况下,我会过滤我的数组,以便它在屏幕上呈现更少的“砖块”。

我的问题是:过滤数组时,我没有删除从“brickRefs”对象中过滤的元素 - 我看到它仍然存在,值为 null;

从 ref 的对象中完全删除它的正确方法是什么?

//initial ref and state: 
const bricksRef = useRef({});
const [bricks, setBricks] = useState([]);
   

  useEffect(() => {
    // initializing bricks data
    const bricksData = getBricks(NUMBER_OF_BRICKS);
    setBricks(bricksData);
}, [])

// filtering the array under some conditions :
const isHittedBrick = (nextTopPos, nextLeftPos) => {     
    const brickHitted = Object.entries(bricksRef.current).filter(([key, value]) => {
        ... returning true under some conditions
    }).map(([id]) => id)
    setBricks(bricks => bricks.filter(b => !brickHitted.includes(b.id)))
}

//render while setting all divs into the refs object:
   return (
    <section className='bricks'>
        {
            bricks.map(b => {
                return <div key={b.id} className='brick' ref={ref => bricksRef.current[b.id] = ref}>
                    {b.id}
                </div>
            })
        }
    </section>
)

【问题讨论】:

    标签: javascript html reactjs react-hooks ref


    【解决方案1】:

    filter,就在return 之前,从引用对象中删除false

    const brickHitted = Object.entries(bricksRef.current).filter(([key, value]) => {
            if (false under some conditions) delete bricksRef.current[key] // if I understand correctly and b.id === key
            ... returning true under some conditions
        }).map(([id]) => id)
    

    更多关于deletehttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

    【讨论】:

    • 直接修改 refs 对象没有问题吗?
    • 其实bricksRef.current[b.id] = ref也是直接变异的:)
    • 你说得对(:删除感觉有点硬核哈哈..谢谢
    猜你喜欢
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多