我正在尝试使用useState钩子填充数组。这个项目是用Next.js和Tailwind制作的。
在map函数的每次迭代中,我想在数组的末尾添加一个元素,直到没有剩余的元素。
我的目标是有一个充满项目的有状态数组,这样我就可以操作所有的项目。
谢谢。
index.js
import { useState } from "react";
import Head from "next/head";
import Image from "next/image";
import requests from "../components/requests";
import Content from "../components/Content";
import Header from "../components/Header";
export const getStaticProps = async () => {
const res = await fetch("https://pokeapi.co/api/v2/pokemon?limit=2000/");
const pokemonData = await res.json();
return {
props: { pokemon: pokemonData },
};
};
export default function Home({ pokemon }) {
return (
<>
<Header />
<main className="flex flex-col items-center justify-center sm:flex-row sm:flex-wrap">
{pokemon.results.map((pokemon) => (
<Content key={pokemon.name} pokemon={pokemon} />
))}
</main>
</>
);
}
Content.js
import React, { useState, useEffect } from "react";
import Image from "next/image";
const Content = ({ pokemon }) => {
const [Pokemon, setPokemon] = useState({ name: [] });
// name.forEach((name) => name[0].toUpperCase() + name.substring(1));
const url = pokemon.url;
const pokemonIndex = url.split("/")[url.split("/").length - 2];
const imageUrl = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemonIndex}.png`;
useEffect(() => {
setPokemon((prevState) => ({
...prevState,
name: prevState.name.concat(pokemon.name),
}));
}, [pokemon]);
console.log(Pokemon);
return (
<div className="p-5">
<h1 className="text-center text-3xl font-bold">{pokemon.name}</h1>
{/* <Image src={Pokemon.imageUrl} width="250" height="250" /> */}
</div>
);
};
export default Content;
您可以创建一个新的数组,并将旧数组的内容与末尾添加的新元素展开。
useEffect(() => {
setPokemon((prevState) => ({
...prevState,
name: [
...preveState.name,
pokemon.name
]
}));
}, [pokemon]);
我假设,您想要完整的口袋妖怪列表(口袋妖怪.results)在Content组件中。一种更简单的方法是将一个单独的道具pokemons={pokemons.results}
传递给Content组件。