我正在做一个尝试获取请求的自定义钩子。我需要输入response使其可重用。
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,
}
答案 0 :(得分:1)
使您的组件通用吗?
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 | {}
,这会使状态用处不大,但是解决方案取决于应用程序,具体取决于您想做什么。
答案 1 :(得分:0)
为您的州设置类型:
const [response, setResponse] = useState<IResponse|{}>({});
const [error, setError] = useState<object|{}>({});