【发布时间】:2022-01-21 16:09:17
【问题描述】:
我已将 JSON 端点转换为 JavaScript 数组,并通过它进行映射以获取所需的键值。 4 个中有 3 个是文本值,但第一个是图像,它只显示 URL 链接。我试图通过同一个数组进行映射并仅显示图像并且它可以工作,但是我无法将这两个元素合并到一个 div 中。
代码:
export default function Pokes() {
const [pokemonData, setPokemonData] = React.useState({});
React.useEffect(() => {
fetch(
"https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json"
)
.then((res) => res.json())
.then((data) => setPokemonData(data.pokemon));
}, []);
const allPokes = pokemonData;
const pokemons = Object.values(allPokes);
const pokesData = pokemons.map(pokemon => `${pokemon.img} ${pokemon.num} ${pokemon.name} ${pokemon.type}`);
let renderedOutput = pokesData.map(item => <div className="infodiv" style={{ flex: 1, flexBasis: "33%" }}> {item} </div>)
return (
<main>
<div>
<div style={{ display: "flex", flexWrap: "wrap" }}>{renderedOutput}</div>
</div>
</main>
);
}
【问题讨论】:
-
你需要
<img>元素并使用 url 设置src
标签: javascript arrays reactjs json react-hooks