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

React的map方法内如何跳过索引0实现条件渲染

React跳过索引0卡片渲染的实现方法

直接在map的渲染回调里加索引判断即可,React遇到返回null的列表项会自动跳过渲染,不会生成多余DOM,也不会打乱原有索引和图片地址的对应关系,是最适配你当前代码的方案。

修改后的完整代码如下:

return (
    <section>
        {pokemonCards.map((pokemon, index) => {
            // 索引为0时直接返回null,不渲染对应卡片
            if (index === 0) return null;
            return (
                <div key={index}>
                    <img 
                        src={`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${index}.png`} 
                        alt={pokemon.name}/>
                    <p>{pokemon.name}</p>
                </div>
            )
        })}
        <button 
            className="get-more-button" 
            onClick={getMorePokemons}>Get more pokemons
        </button>
    </section>
)

注意事项

  • 不推荐先过滤数组再遍历的写法:你当前代码的图片地址是直接用遍历索引拼接的,如果提前截断数组去掉第一项,后续所有项的索引都会向前偏移1位,会导致所有宝可梦图片和名称对应错误。如果一定要提前过滤,需要额外保留原始索引值,写法更繁琐,没有必要。
  • 不要用CSSdisplay: none隐藏第一项:这种方式依然会发起图片资源请求、生成DOM节点,只是视觉上不可见,会造成不必要的资源浪费。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 08:06:20