【发布时间】:2021-04-18 19:41:16
【问题描述】:
我正在使用 React 来显示一组图像。正在从数据库中检索图像 URL,因此我希望它们不会立即出现,一旦加载它们就会作为道具传递给该组件。
为了防止这导致错误,如果数组未定义,我使用了两个短路运算符来防止映射运行,但函数仍在运行并返回无法读取未定义的属性“映射”。任何想法为什么?有时当我刷新页面时它会起作用。
{
images !== undefined && images.length > 1 &&
<React.Fragment>
<ImageCarouselBtnForward icon={ faChevronRight } onPointerDown={() => incrementer(images, activeImage, '+')}/>
<ImageCarouselBtnBack icon={faChevronLeft} onPointerDown={() => incrementer(images, activeImage, '-')}/>
<ImageCarouselSlideIndicatorGroup>
{
images !== undefined &&
images.map((e, idx) => (
<ImageCarouselSlideIndicator
idx={idx}
activeImage={activeImage}
arrLength={images.length}
onPointerDown={() => incrementer(images, activeImage, null, idx)}
/>
))
}
</ImageCarouselSlideIndicatorGroup>
</React.Fragment>
}
非常感谢任何帮助。
【问题讨论】:
-
这表明您在其他地方遇到了此错误,而不是在显示的代码中。 (不太可能:
undefined已被屏蔽。)另外,与其明确测试undefined,我可能只使用真实测试:images && images.length > 1 && ...(你不需要另一个)。 -
你试过用普通的
if condition吗? -
我想知道
images?.map是否可行。可能会使用 != undefined 。除非你用 [] 初始化你的数组,在这种情况下它还需要一个长度测试
标签: javascript reactjs styled-components