useState Hook - 如何将项目附加到有状态数组的末尾?

时间:2021-07-25 06:16:46

标签: javascript reactjs react-hooks next.js use-state

我正在尝试使用 useState Hook 填充数组。这个项目是用 Next.js 和 Tailwind 制作的。

在 map 函数的每次迭代中,我想在数组的末尾添加一个项目,直到没有剩余项目为止。

我的目标是拥有一个充满项目的有状态数组,以便我可以操作所有项目。

谢谢。

index.js

df_final = df_months.withColumn("ToKeep",func.when(df_months.monthDiff.isNull(),1 ).when(df_months.monthDiff>6,1).otherwise(0))

Content.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>
    </>
  );
}

2 个答案:

答案 0 :(得分:1)

您可以创建一个新数组,并在末尾添加新元素的情况下扩展旧数组的内容。

useEffect(() => {
    setPokemon((prevState) => ({
      ...prevState,
      name: [
        ...preveState.name,
        pokemon.name
      ]
    }));
  }, [pokemon]);

答案 1 :(得分:0)

我假设您希望在内容组件中包含 pokemons (pokemon.results) 的完整列表。一种更简单的方法是将单独的 prop pokemons={pokemons.results} 传递给 Content 组件。

相关问题