相关疑难解决方法(0)

React Hook 依赖项 - 通用 Fetch Hook

我已经学习了许多关于如何设置我自己的自定义通用useFetch钩子的教程。我想出来的东西很好用,但它打破了一些钩子规则。大多数情况下,它不使用“正确”的依赖项集。

通用钩子接受 url、选项和依赖项。将依赖项设置为所有三个会创建一个无限刷新循环,即使依赖项没有改变

// Infinite useEffect loop - happy dependencies
const UseRequest: <T>(url: string, options?: Partial<UseRequestOptions> | undefined, dependencies?: any[]) => UseRequestResponse<T>
 = <T>(url: string, options: Partial<UseRequestOptions> | undefined = undefined, dependencies: any[] = []): UseRequestResponse<T> => {
    const [data, setData] = useState<T | undefined>();
    const [loading, setLoading] = useState<boolean>(false);
    const [error, setError] = useState<UseRequestError | undefined>();

    useEffect(() => {
        let ignore = false;
        (async () => {
            try {
                setLoading(true);
                const response = await (options …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

10
推荐指数
1
解决办法
338
查看次数

标签 统计

react-hooks ×1

reactjs ×1