[英]'Cannot read property 'map' of undefined' even though I explicitly told it not to run the function if array is undefined
I'm using React to display an array of images.我正在使用 React 来显示一组图像。 The image URLS are being retrieved from a database so I'm expecting them not to be there immediately, once loaded they're being passed as props to this component.
图片 URLS 是从数据库中检索的,所以我希望它们不会立即出现,一旦加载它们就会作为道具传递给这个组件。
To prevent this causing an error I used two short circuit operators to prevent the map running if the array is undefined, but the function is still running and returning Cannot read property 'map' of undefined.为了防止这导致错误,我使用了两个短路运算符来防止 map 在数组未定义时运行,但 function 仍在运行并返回无法读取未定义的属性“映射”。 Any ideas why?
任何想法为什么? Sometimes it works when I refresh the page.
有时它会在我刷新页面时起作用。
{
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>
}
Any help is greatly appreciated.任何帮助是极大的赞赏。
Try images.= undefined.尝试图像。=未定义。
Or initialize images with [].或者用 [] 初始化图像。 and you do not have to put that undefined check.
而且您不必进行未定义的检查。 You just need images.length check.
你只需要 images.length 检查。
As a work around I moved the short circuit up to the parent element to prevent the entire component rendering until the image array is available.作为解决方法,我将短路向上移动到父元素,以防止在图像数组可用之前渲染整个组件。
To fix the original issue I initialised images as an empty array.为了解决最初的问题,我将图像初始化为一个空数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.