首页 > 解决方案 > 无法在反应响应轮播中执行条件渲染

问题描述

我在 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 组件内部的条件会引发该错误。

标签: javascriptreactjscarousel

解决方案


推荐阅读