You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何遍历含3个useMemo返回值的Props渲染轮播告警?

问题:React轮播组件中遍历渲染动态告警内容报错

开发用户仪表盘时,通过3个useMemo函数分别生成不同类型的告警组件,满足条件时显示在仪表盘顶部;存在多个需显示的告警时,放入自动轮播组件中。已创建Slideshow组件并将3个useMemo的返回值作为Props传入,但尝试用props.map遍历渲染告警时出现报错,寻求正确的遍历实现方式。


问题根源

你传入Slideshow的是三个独立的Props(对象属性),而非数组,而map是数组方法,无法直接遍历对象,因此触发报错。


解决方案

步骤1:在TransactionsPage中整理告警组件为数组

将三个useMemo生成的告警组件收集到一个数组中,过滤掉不满足条件的空值,再统一传入Slideshow:

// 在TransactionsPage组件中添加以下代码
const warnings = useMemo(() => {
  return [
    renderMaxManualTransactionWarning,
    renderMissingTransferTransactionWarning,
    renderSuggestedLinksWarning
  ].filter(Boolean); // 过滤掉未满足条件的空/undefined值
}, [renderMaxManualTransactionWarning, renderMissingTransferTransactionWarning, renderSuggestedLinksWarning]);

// 修改Slideshow的调用方式
return (
  <LoggedInLayout className={"transactions-page"}>
    <Slideshow warnings={warnings} />
  </LoggedInLayout>
);

步骤2:修改Slideshow组件适配数组格式

调整Slideshow组件,接收warnings数组作为Props,动态处理轮播逻辑(包括指示器数量、自动轮播触发条件):

/* eslint-disable no-unused-vars */
import React, { useEffect, useState, useRef } from "react";
import "./index.scss";
import PropTypes from "prop-types";

const delay = 10000;

export const Slideshow = ({ warnings }) => {
  const [index, setIndex] = useState(0);
  const timeoutRef = useRef(null);

  // 无告警时直接返回空,避免渲染空轮播
  if (!warnings.length) return null;

  function resetTimeout() {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }
  }

  useEffect(() => {
    resetTimeout();
    // 仅当存在多个告警时开启自动轮播
    if (warnings.length > 1) {
      timeoutRef.current = setTimeout(
        () => setIndex((prevIndex) => (prevIndex === warnings.length - 1 ? 0 : prevIndex + 1)),
        delay
      );
    }

    return () => {
      resetTimeout();
    };
  }, [index, warnings.length]);

  return (
    <div className={"slideshow"}>
      <div className={"slideshowSlider"} style={{ transform: `translate3d(${-index * 100}%, 0, 0)` }}>
        {warnings.map((warning, idx) => (
          <div key={idx} className="slide">
            {warning}
          </div>
        ))}
      </div>

      {/* 仅当存在多个告警时显示切换指示器 */}
      {warnings.length > 1 && (
        <div className={"slideshowDots"}>
          {warnings.map((_, idx) => (
            <div
              key={idx}
              className={`slideshowDot${index === idx ? " active" : ""}`}
              onClick={() => setIndex(idx)}
            ></div>
          ))}
        </div>
      )}
    </div>
  );
};

Slideshow.propTypes = {
  warnings: PropTypes.arrayOf(PropTypes.node),
};

export default Slideshow;

关键优化点

  1. 数组化处理告警:将分散的Props整合为数组,统一遍历渲染,解决对象无法map的问题。
  2. 动态适配轮播逻辑:根据告警数量自动控制是否开启轮播、是否显示指示器,提升用户体验。
  3. 空值过滤:通过filter(Boolean)确保轮播中只包含有效告警组件,避免渲染空内容。

内容的提问来源于stack exchange,提问作者Asher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:01:02