javascript 在map方法内部进行React条件渲染

pgccezyw  于 2023-02-15  发布在  Java
关注(0)|答案(2)|浏览(136)

我有下面的代码,我想应用条件渲染,因为索引0不存在。我不想渲染这个特定索引的信息。我该怎么做呢?

return (
        <section>
            {pokemonCards.map((pokemon, index) =>             
                <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>
    )
vcudknz3

vcudknz31#

这应该行得通:

return (
        <section>
            {pokemonCards.map((pokemon, index) =>             
                {index === 0 ? null : <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>
    )
olhwl3o2

olhwl3o22#

如果您不想为不存在的口袋妖怪渲染一个空的div,您可以执行以下操作:

return (
    <section>
      {pokemonCards.map(
        (pokemon, index) =>
          index !== 0 && (
            <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>
  );

相关问题