我创建了一个名为useFetch的自定义挂钩。
import { useState, useEffect } from 'react'
export const useFetch = (url: string, options?: object) => {
const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
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
并使用typescript键入它失败了,就好像答案可能是空一样
import React, { FunctionComponent } from 'react'
import { useFetch } from '../../hooks/useFetch'
export const ListOfMovies: FunctionComponent = () => {
const { response, error }: { response: object, 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>
)
}
- 您可以尝试手动将响应设置为"any">
import { useState, useEffect } from 'react'
export const useFetch = (url: string, options?: object) => {
const [response, setResponse] = useState<any>(null);
const [error, setError] = useState<any>(null);
...
};
如果您不喜欢"any",请尝试使用泛型。
export const useFetch = <T>(url: string, options?: object) => { const [response, setResponse] = useState<T>(null); const [error, setError] = useState<T>(null); ... };
}
所以函数调用看起来像
type YourCustomType = {response: ..., error: ...}
const { response, error }: { response: object, error: object} =
useFetch<YourCustomType>("http://www.omdbapi.com/?apikey=****&s=batman&page=2");
}
您已将响应和错误的初始值设置为null,因此会收到此警告。
试试这个:
const [response, setResponse] = useState({});
const [error, setError] = useState({});