如何在react js中为usestate中的对象数组创建接口

问题描述

我使用 AXIOS 向服务器发出请求,然后服务器返回如下值:

enter image description here

我想将它保存在状态中,这里我使用反应钩子,当我想用​​数据设置状态时,我得到错误

Argument of type '() => IterableIterator<IMahasiswa>' is not assignable to parameter of type 'SetStateAction<undefined>'.
  Type 'IterableIterator<IMahasiswa>' is not assignable to type 'undefined'.ts(2345)

这是我的代码

enter image description here

和我的界面:

enter image description here

如何设置 setMahasiswa 的接口我已经尝试过 <IMahasiswa[]> 但它给出了同样的错误,只是在 res.values 部分它被替换为 {{1} } 它成功返回,但是当我使用 map 进行循环时它会抛出另一个错误

解决方法

我的假设是您的 axios.get(url[,config]) 默认返回 any 类型。因此,除非您将其强制转换为 data,否则您的 any 也有 IMahasiswa[] 类型。

不过,我建议的解决方案是在 axios.get 处定义类型,这是他们的 typedef 的大纲。

export interface AxiosInstance {
  //...
  get<T = any,R = AxiosResponse<T>>(url: string,config?: AxiosRequestConfig): Promise<R>;
  //...
}

因此,您可以这样做;

await axiosClient.get<IMahasiswa[]>("asd/asd",{});

这是完整的代码示例;

interface IMahasiswa {
  name: string;
  age: number;
}

const useTest = () => ({
  async fetch(): Promise<IMahasiswa[]> {
    const { data } = await axiosClient.get<IMahasiswa[]>("asd/asd",{});
    return data; // data here has the type of IMahasiswa[]
  },});

const axiosClient = axios.create({
  baseURL: "http://localhost:1231",});

const TestComp = () => {
  const [mahasiswa,setMahasiswa] = React.useState<IMahasiswa[]>([]);
  const testFn = useTest();

  useEffect(() => {
    testFn.fetch().then((res) => {
      setMahasiswa(res);
    });
  },[]);

  return <div>asd</div>;
};