TypeError:无法读取长度未定义的属性?-React旋转木马



在这里学习本教程正是因为我想在我的网站上使用这个旋转木马。

然而,我得到了错误";TypeError:无法读取未定义的属性";,即使代码与教程完全相同,教程讲师也从未遇到过此错误。

  1. 如何解决此问题
  2. 为什么我会出现这个错误,而辅导老师却没有?发现很难理解这是怎么发生的——视频仅来自2020年12月

提前感谢。

以下代码:

import React, {useState} from 'react';
import styled from 'styled-components'
import { CarouselData } from '../Data/CarouselData';
import {FaArrowAltCircleRight, FaArrowAltCircleLeft} from 'react-icons/fa';
export const Carousel = ({slides}) => {
const [current, setCurrent] = useState(0);
const length = slides.length;
const nextSlide = () => {
setCurrent(current === length -1 ? 0 : current + 1)
}
const prevSlide = () => {
setCurrent(current === length -1 ? 0 : current + 1);
}
console.log(current);
if (!Array.isArray(slides) || slides.length <= 0){
return null;
}

return (
<div>
<Section>
<LeftArrow >
<FaArrowAltCircleLeft onClick={prevSlide}/>
</LeftArrow>
{CarouselData.map((slide, index) => {
return(
<img style={{width: "400px", height: "600px", borderRadius: "10px"}} src={slide.image} alt="image" />
)
})}
<RightArrow >
<FaArrowAltCircleRight onClick={nextSlide}/>
</RightArrow>
</Section>

</div>
)
}
const Section = styled.div`
position: relative;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
`
const LeftArrow = styled.div`
position: absolute;
top: 50%;
left: 32px;
font-size: 3rem;
color: white;
z-index: 10;
cursor: pointer;
user-select: none;
`
const RightArrow = styled.div`
position: absolute;
top: 50%;
right: 32px;
font-size: 3rem;
color: white;
z-index: 10;
cursor: pointer;
user-select: none;
`
const Image = styled.div`
display: inline-block;
width: 100px;
height: 400px;
border-radius: 10px;
`

附言-如果需要一个代码沙盒,我会做一个,但这是一个小代码文件和小问题,所以不认为需要

错误来自于没有将幻灯片作为道具放在父组件PortfolioPage中。

请参阅下面的代码-在我的函数PortfolioPage的括号为空之前-因此,为什么幻灯片现在是未定义的,一旦添加了幻灯片,它就被定义了。


export const PortfolioPage = (slides) => {
return (
<div style={{ height: "100vh"}}>
<Container>
<Grid container>
<Grid item md={6}>
<TopSection>
</TopSection>
</Grid>
<Grid item md={6}>
<BottomSection>
<Carousel slides={CarouselData}/>


</BottomSection>
</Grid>
</Grid>
</Container>
</div>
)
}

最新更新