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
相关产品推荐
相关产品推荐

