javascript - 无法在反应响应轮播中执行条件渲染
问题描述
我在 React 中循环遍历一个数组并有条件地返回 carousel 组件内部。
代码:
projects.map((proj) => {
if(proj.active){
return (
<Carousel emulateTouch swipeable useKeyboardArrows infiniteLoop>
<ProjectItemMob singleProject={proj} />
</Carousel>
);
}
})
这给了我一个错误: Uncaught TypeError: Cannot read property 'type' of null
有什么修复吗?它在没有条件的情况下工作,但我需要添加条件。
编辑:
首先,根据条件过滤数组并更新状态。
const [allEnabledProjects, setallEnabledProjects] = React.useState([]);
React.useEffect(() => {
if (projects) {
let enabledProjects = projects.filter(
(proj) => proj.isActive === true
);
if (enabledProjects.length > 0) {
setallEnabledProjects(enabledProjects);
} else {
setallEnabledProjects([]);
}
}
}, [projects]);
之后,使用过滤后的数组进行映射,这样我们就不必将条件放在 Carousel 组件中。
allEnabledProjects.map((proj) => {
return (
<Carousel emulateTouch swipeable useKeyboardArrows infiniteLoop>
<ProjectItemMob singleProject={proj} />
</Carousel>
);
})
尽管我能够使用不同的方法并且它正在工作,但我仍然无法弄清楚为什么 Carousel 组件内部的条件会引发该错误。
解决方案
推荐阅读
- bash - 如何在最后一个空行之后从文件中获取所有行?
- firebase - Xamarin 和推送通知 - 使用 Azure 通知中心的原因?
- windows - 如何为 Windows 机器配置 aws elb
- java - 按下后退按钮时使用 MainActivity 登录 Activity
- ruby - 使用 Restful Ruby 获取 Instagram 访问令牌
- node.js - 如何解决在构建我的 Angular 应用程序时发生的这个错误?
- sql - 如何根据每天的设备使用情况对 id 进行分段
- javascript - 传输的 getUserMedia/MediaRecorder 视频格式大于请求的格式。怎么讲?
- python - Pandas Dataframe 删除了很多行
- r - Group_by (dplyr) 以一个因子为列