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

Preact组件循环内部元素无法渲染,请求排查原因

问题分析与修复方案

你的问题出在外层map回调函数没有返回内层map的结果,而且内层map被多余的大括号包裹,导致组件没有生成任何子元素。

具体原因:

  • 外层map的箭头函数用了大括号{},这种情况下必须显式用return返回要渲染的内容,但你只是在代码块里执行了内层map,没有返回它的结果,所以外层map的每一项都返回undefined,最终父容器里没有可渲染的内容。
  • 内层map外面的额外大括号{[...Array(height)].map(...)}完全多余,这会被当成无意义的代码块,不会被当作渲染内容处理。

两种修复方法:

方法1:去掉外层回调的大括号,让箭头函数隐式返回

export const Grid = ({ width, height }: { width: number, height: number }) => {
    const [grid] = useState<Cell[]>(initialiseArray({ width, height, fill: () => ({ active: Math.random() < 0.5 }) }));

    return (
        <div>
            {[...Array(width)].map((_, indexX) =>
                [...Array(height)].map((_, indexY) => (
                    <div 
                        key={indexX * height + indexY}
                        style={{ backgroundColor: grid[indexX * height + indexY].active ? "red" : "white" }}
                    >
                        X
                    </div>
                ))
            )}
        </div>
    );
};

方法2:保留外层大括号,显式添加return

export const Grid = ({ width, height }: { width: number, height: number }) => {
    const [grid] = useState<Cell[]>(initialiseArray({ width, height, fill: () => ({ active: Math.random() < 0.5 }) }));

    return (
        <div>
            {[...Array(width)].map((_, indexX) => {
                // 显式返回内层map生成的元素数组
                return [...Array(height)].map((_, indexY) => (
                    <div 
                        key={indexX * height + indexY}
                        style={{ backgroundColor: grid[indexX * height + indexY].active ? "red" : "white" }}
                    >
                        X
                    </div>
                ));
            })}
        </div>
    );
};

额外提示:给每个子元素加上唯一的key属性(比如用indexX * height + indexY),可以避免Preact的性能警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:09:12