我尝试根据Gatsby在我的应用中创建Carousel。我在将道具从“父级”传递给“子级”功能组件时遇到问题。我收到错误TypeError:props.slide is undefined但是当我在控制台中检查日志时,我可以看到props.slide具有价值
我只想知道显示空道具的控制台的第一行(上面的截图),对吧?奇怪的是,codesandbox没有给出任何错误:https://codesandbox.io/s/ecstatic-snyder-9hjpf
父组件:
//imports...
const carouselItems = [
{
title: "Laser scanning",
picture: "../../../../assets/images/RTC360.png",
content:
"Lorem ipsum dolor sit amet, consectetur adipisicing elit. A ad deserunt, enim est exercitationem facilis illum ipsum iure, mollitia placeat quia temporibus voluptatem. Asperiores assumenda id nesciunt totam. Eligendi, neque."
},
{
title: "Mobile mapping",
picture: "../../../../assets/images/RTC360.png",
content:
"Lorem ipsum dolor sit amet, consectetur adipisicing elit. A ad deserunt, enim est exercitationem facilis illum ipsum iure, mollitia placeat quia temporibus voluptatem. Asperiores assumenda id nesciunt totam. Eligendi, neque."
}
];
interface CarouselState {
activeIndex: number;
}
class Carousel extends React.Component<any, CarouselState> {
constructor(props: any) {
super(props);
this.state = {
activeIndex: 0
};
}
render() {
return (
<div>
<ul>
{carouselItems.map((slideDescription, index) => (
<CarouselDescriptionRCTypes
key={index}
index={index}
activeIndex={this.state.activeIndex}
slide={slideDescription}
/>
))}
</ul>
</div>
);
}
}
export default Carousel;
子组件:
//imports...
interface CarouselDescriptionProps {
index: number;
activeIndex: number;
slide: {
title: string;
picture: string;
content: string;
};
}
const CarouselDescriptionRCTypes: React.FC<
CarouselDescriptionProps
> = props => {
if (!props) {
return null;
}
console.log(`props${JSON.stringify(props)}`);
console.log(`props.slide.title${props.slide.title}`);
return (
<div>
<strong className="carousel-slide__author">{props.slide.title}</strong>
<small className="carousel-slide__source">{props.slide.content}</small>
</div>
);
};
export default CarouselDescriptionRCTypes;
@@ Shlang回答了我的问题。我一直在通过
检查IF子句中的props if (!props) {
return null;
}
始终返回true,因为props始终是对象,并且永远不会被不确定。我相信检查道具会防止返回未定义的错误,这是错误的。
正如@Shlang所提到的,应该使用相同的子句来检查prop中的每个值,例如:
if (!props.slide) {
return null;
}
,或使用例如Lodash库及其isEmpty函数。