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

React中如何正确遍历数组?使用for...of遇非可迭代对象报错

React中正确遍历数组匹配产品的解决方案

核心问题分析

  1. for...of报错原因:你传入的category props大概率不是可迭代的数组类型(比如是单个字符串、对象或undefined),for...of仅支持数组、字符串、Map等可迭代对象,非可迭代类型直接使用就会触发报错。
  2. 现有代码的逻辑缺陷:
    • 用products.map嵌套循环时,未匹配到分类的产品会返回undefined,React会将这些undefined渲染为空节点,造成不必要的性能损耗。
    • 手动循环的写法冗余,不如数组内置方法简洁直观。

正确实现方式

推荐先通过filter筛选出符合分类条件的产品,再用map渲染组件,逻辑更清晰,也避免了无效渲染:

import React, { useEffect, useRef } from "react";
import "./productLists.css";
import products from "../../data/products.json";
import { useSlider } from "../../hooks/useSlider";
import Card from "../Card/Card";
import PropTypes from 'prop-types'; // 可选,用于类型校验

const ProductLists = ({ head, title, category }) => {
    const sliderLineRef = useRef();
    const [init] = useSlider(sliderLineRef, 400);

    useEffect(() => {
        init();
    }, []);

    // 筛选匹配分类的产品
    const matchedProducts = products.filter(product => {
        // 处理category为数组的情况:检查产品分类是否在数组中
        if (Array.isArray(category)) {
            return category.includes(product.category);
        }
        // 处理category为单个字符串的情况:直接对比
        return product.category === category;
    });

    return (
        <div className="productList container">
            <h3 className="head">{head}</h3>
            <h2 className="title">{title}</h2>

            <div ref={sliderLineRef} className="productList__list row">
                {matchedProducts.map((p) => (
                    // 优先使用产品的唯一ID作为key,而非索引,提升渲染性能
                    <Card key={p.id} product={p} />
                ))}
            </div>
        </div>
    );
};

// 可选:添加props类型校验,提前发现类型错误
ProductLists.propTypes = {
    head: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
    category: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.arrayOf(PropTypes.string)
    ]).isRequired,
};

export default ProductLists;

对原有代码的优化说明

  • 替换手动循环为includes:数组的includes方法可以直接判断元素是否存在,比for...in/for...of更简洁,且自动处理数组类型的校验。
  • 先筛选再渲染:filter会直接生成符合条件的产品数组,避免map返回undefined导致的空节点渲染。
  • 优化key值:使用产品的唯一ID(如p.id)替代索引作为key,确保React在产品顺序变化时能正确复用组件,提升渲染效率。

额外注意事项

  • 确认父组件传入的category类型:如果是单个分类值,直接对比即可;如果是多个分类的数组,用includes判断。
  • 若category可能为undefined,需在filter中添加兜底判断,避免报错:
    const matchedProducts = products.filter(product => {
        if (!category) return false;
        // ...原有逻辑...
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:05:31