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

NextJS与TypeScript环境下传递SetState函数给组件时的类型错误求助

NextJS与TypeScript环境下传递SetState函数给组件时的类型错误求助

我来帮你解决这个类型错误问题,先拆解下你代码里的几个核心问题:

  • 组件调用方式错误:你把FetchPokeAPI当成普通函数直接调用了,但它是一个React组件,必须用JSX标签的方式渲染,并且传递符合接口定义的props对象。
  • Props接口冗余且调用不匹配:你的IProps接口定义了allItems属性,但FetchPokeAPI组件里根本没用到它,而且你调用的时候只传了setAllItems,这就导致了类型不匹配——因为IProps要求是包含两个属性的对象,而你传的是单个Dispatch函数。
  • 接口定义语法错误:IAllItems的定义最后多了[];,这是无效的TypeScript语法,应该修正。
  • useEffect依赖问题:FetchPokeAPI里的useEffect依赖数组应该加上setAllItems,避免不必要的重渲染或者遗漏更新。

修正后的代码

/index.tsx

import { Dispatch, SetStateAction, useState } from "react";
import FetchPokeAPI from "./api/FetchPokeAPI";
import Header from "./components/Header";
import ItemList from "./components/ItemList";

// 修正接口定义的语法错误
export interface IAllItems {
  name: string;
  url: string;
}

export default function Home() {
  const [allItems, setAllItems] = useState<IAllItems[]>([]);

  return (
    <>
      <Header />
      {/* 用JSX标签渲染组件,传递正确的props */}
      <FetchPokeAPI setAllItems={setAllItems} />
      <ItemList items={allItems} />
    </>
  );
}

/api/FetchPokeAPI.tsx

import { Dispatch, SetStateAction, useEffect } from "react";
import { IAllItems } from "./../index";

// 移除不需要的allItems属性,只保留用到的setAllItems
interface IProps {
  setAllItems: Dispatch<SetStateAction<IAllItems[]>>;
}

export default function FetchPokeAPI({ setAllItems }: IProps) {
  const pokeapiURL: string = "https://pokeapi.co/api/v2/item/";

  useEffect(() => {
    fetch(pokeapiURL)
      .then((response) => response.json())
      .then((data) => {
        setAllItems(data.results);
      })
      .catch((error) => console.error(error));
  }, [pokeapiURL, setAllItems]); // 添加setAllItems到依赖数组
}

修正说明

现在FetchPokeAPI作为组件被正确渲染,props传递完全符合接口要求,类型错误自然就解决了;同时移除了冗余的属性定义、修正了语法错误,也完善了hooks的依赖规范,保证代码的稳定性和可读性。

备注:内容来源于stack exchange,提问作者CapCo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 15:32:44