Javascript 使用带有typescript和axios的fetch钩子
我有一个关于使用typescript和Axios实现useFetch钩子的问题 下面是我找到的一些示例UseFetchHook。但它是一个javascript实现。我只是给了他们一些回应和错误 这是我的useFetch hook.ts文件Javascript 使用带有typescript和axios的fetch钩子,javascript,reactjs,typescript,axios,Javascript,Reactjs,Typescript,Axios,我有一个关于使用typescript和Axios实现useFetch钩子的问题 下面是我找到的一些示例UseFetchHook。但它是一个javascript实现。我只是给了他们一些回应和错误 这是我的useFetch hook.ts文件 import { useState, useEffect } from 'react' export const useFetch = ({ api, method, url, data = null, config
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>
)
返回(
{response&&response.id}
)
下面是标题部分
type Props = {
children: string
}
export const Title: FC<Props> = ({ children }) => {
return <h4>{children}</h4>
}
类型道具={
儿童:字符串
}
导出常量标题:FC=({children})=>{
返回{children}
}
我得到这个错误:
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)
Type'null'不能分配给Type'string |(string&{})|(string&ReactElement-ReactElement-Component)>| null)|(new(props:any)=>Component)>)|(string&ReactNodeArray)|(string&ReactPortal);.ts(2322)
对象可能为“null”。ts(2531)
这是我如何以一种类型脚本的方式实现这个钩子的第一个问题
这里使用fetchapi。如何在这里使用Axios?我认为您目前有两个问题需要解决,如下所示:
- 在自定义钩子中,您使用state
告诉const[response,setResponse]=useState(null)
始终response
,这可能会导致您在这里检查null
的问题。因此,我建议您在泛型类型中填写响应类型:{response&&response.id}
export const useFetch=({
应用程序编程接口,
方法,,
网址,
数据=空,
config=null,
}:any)=>{
const[response,setResponse]=useState(null);//将`R`设置为返回的类型
// ...
}
然后指定使用自定义挂钩的响应:
const{response,isload,error}=useFetch({
// ...
});
- 另一件需要改进的事情是
类型应该是子类
React.ReactNode
类型道具={
子项:React.ReactNode
}
子项:string | null
是否需要添加每个类型| null?我认为这不太正确,不是吗?response&&response.id
可以是null
(在请求完成之前),所以您有两个选项:允许子项为null
或提供一些回退(例如response?.id???
)@user3348410旁注:当您使用FC
时,无需显式键入子项