【发布时间】:2021-04-15 12:07:25
【问题描述】:
我有一个关于使用 typescript 和 Axios 实现 useFetch 钩子的问题。
这是我找到的一些示例 useFetch 钩子。但这是一个 javascript 实现。我只是给了那里任何回应和错误。
https://codesandbox.io/s/react-fetch-hook-gtiec?from-embed=&file=/src/components/App.js
这是我的 useFetch 挂钩 .ts 文件。
import { useState, useEffect } from 'react'
export const useFetch = ({
api,
method,
url,
data = null,
config = null,
}: any) => {
const [response, setResponse] = useState(null)
const [error, setError] = useState('')
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
const fetchData = async () => {
api[method](url, JSON.parse(config), JSON.parse(data))
.then((res : any) => {
setResponse(res.data)
})
.catch((err : any) => {
setError(err)
})
.finally(() => {
setIsLoading(false)
})
}
fetchData()
}, [api, method, url, data, config])
return { response, error, isLoading }
}
这是我通过 useFetch 发出获取请求的组件。
const { response, isLoading, error } = useFetch({
api: BaseURL,
method: 'get',
url: 'some',
})
一切正常的请求是有效的。 但是当我尝试将响应中的一些字符串值传递给我的某个子组件(子组件等待字符串值)时。
这是我发出获取请求的组件中的子组件。
return (
<Title>{response && response.id}</Title>
)
这里是标题组件
type Props = {
children: string
}
export const Title: FC<Props> = ({ children }) => {
return <h4>{children}</h4>
}
我收到此错误:
Type 'null' is not assignable to type 'string | (string & {}) | (string & ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)>) | (string & ReactNodeArray) | (string & ReactPortal)'.ts(2322)
Object is possibly 'null'.ts(2531)
这是我如何以打字稿方式实现这个钩子的第一个问题。
这里使用 fetch API。我怎么可以在这里使用 Axios?
【问题讨论】:
-
children: string | null -
我需要添加每种类型吗?空值?我认为这不太正确,不是吗?
-
response && response.id可以是null(在请求完成之前),所以你有两个选择:允许children成为null或提供一些后备(例如response?.id ?? '')跨度>
标签: javascript reactjs typescript axios