简体   繁体   English

将空项目添加到 React 中的引用数组中

[英]Empty items being added to array of refs in React

I have the following code:我有以下代码:

const nodeRefs = useRef<Array<HTMLDivElement | null>>([]);

function setNodeRefs(ref: HTMLDivElement | null, idx: number): void { nodeRefs.current[idx] = ref; }

{nodes.length === 5 && nodes.map((node, idx) => (idx === 1 || idx === 2)
    && (
        <MyComponent
            setNodeRefs={setNodeRefs}
            idx={idx}
            key={String(`${idx}-${uuidv4()}`)}
            className="h__node"
        />
    ))}

However the resulting array of refs includes an empty item:然而,结果数组 refs 包含一个空项:

[empty, div.h__node, div.h__node] [空,div.h__node,div.h__node]

It seems like a node is being set in the array of refs even when the condition inside the map is not met.即使不满足 map 内部的条件,似乎也在参考数组中设置了一个节点。

How can I create the array without adding the empty item to it?如何在不向其中添加空项的情况下创建数组?

This is happening because you are setting the elements at indices 1 and 2 respectively, and the 0 th index of your nodeRefs.current array is undefined .发生这种情况是因为您分别在索引12处设置元素,并且nodeRefs.current数组的第0个索引是undefined

Depending on your requirement, subtracting 1 from idx or using Array#push should do.根据您的要求,从idx中减去1或使用Array#push应该可以。

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. map() 方法创建一个新数组,其中填充了在调用数组中的每个元素上调用提供的 function 的结果。

Hence even though you have conditions, the size of the array will remain unchanged when you use .map .因此,即使您有条件,当您使用.map时,数组的大小也将保持不变。 You may want to use.forEach or for-loops.您可能想要使用.forEach 或 for 循环。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

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

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