【问题标题】:useFetch hook with typescript and axios带有 typescript 和 axios 的 useFetch 钩子
【发布时间】: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 &amp;&amp; response.id 可以是null(在请求完成之前),所以你有两个选择:允许children 成为null 或提供一些后备(例如response?.id ?? '')跨度>

标签: javascript reactjs typescript axios


【解决方案1】:

我认为您目前有两个问题需要解决:

  • 在您的自定义钩子中,您使用状态const [response, setResponse] = useState(null),它告诉response 总是null,这可能会导致您在此处查看{response &amp;&amp; response.id} 的问题。所以我建议你用泛型类型填写响应类型:
export const useFetch = <R extends any = any>({
  api,
  method,
  url,
  data = null,
  config = null,
}: any) => {
  const [response, setResponse] = useState<R | null>(null); // set `R` as returned type
  // ...
}

然后,您在使用自定义挂钩的位置指定您的响应:

const { response, isLoading, error } = useFetch<{ id: string }>({
  // ...
});
  • 另一件事是细化是children类型应该是React.ReactNode
type Props = {
    children: React.ReactNode
}

【讨论】:

  • @user3348410 旁注:当您使用FC 时无需显式输入children
猜你喜欢
  • 2020-06-10
  • 2021-11-24
  • 1970-01-01
  • 2022-07-29
  • 2020-06-19
  • 1970-01-01
  • 2021-03-29
  • 2021-09-16
  • 2021-10-21
相关资源
最近更新 更多