如何键入自定义钩子以使其可重复使用



我正在做一个自定义挂钩,尝试获取请求。我需要键入响应以使其可重复使用。

import { useState, useEffect } from 'react'
export function useFetch (url: string, options?: object) {
const [response, setResponse] = useState({});
const [error, setError] = useState({});
useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(url, options);
const json = await res.json();
setResponse(json);
} catch (error) {
setError(error);
}
};
fetchData();
}, []);
return { response, error };
};

当我从组件中使用它时,我会为该答案创建特定的接口,但这就是错误所在。因为在构造useFetch时,我为响应设置的接口与自定义挂钩的类型不同。

Type '{ response: {}; error: {}; }' is not assignable to type '{ response: IResponse; error: object; }'.
Types of property 'response' are incompatible.

这是我导入的组件useFetch

import React, { FunctionComponent } from 'react'
import { useFetch } from '../../hooks/useFetch'
export const ListOfMovies: FunctionComponent = () => {
const { response, error }: { response: IResponse, error: object} = useFetch(
"http://www.omdbapi.com/?apikey=****&s=batman&page=2"
)

if (!response) return <h2>Loading...</h2>
if (error) return <h2>Error</h2>
return (
<div>
<h2>Lista de películas</h2>
{response.Search.map(movie => (
<p>{movie.Title}</p>
))}
</div>
)
}
interface IResponse {
Search: Array<IMovie>
}
interface IMovie {
Title: string,
Year: string,
imdbID: string,
Type: string,
Poster: string,
}

是否使您的组件通用?

export function useFetch<ResponseType>(url: string, options?: object) {
const [response, setResponse] = useState<ResponseType | {}>({});
...

然后称之为:

const { response, error } = useFetch<IResponse>(
"http://www.omdbapi.com/?apikey=****&s=batman&page=2"
)

请注意,如果没有有效的状态默认值,则必须将状态设置为T | {},这会使其不那么有用,但解决方案是特定于应用程序的,具体取决于您想要做什么。

为您的状态设置类型:

const [response, setResponse] = useState<IResponse|{}>({});
const [error, setError] = useState<object|{}>({});

相关内容

  • 没有找到相关文章

最新更新