Web*_*rer 10 reactjs react-hooks
我已经学习了许多关于如何设置我自己的自定义通用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 ? fetch(url) : fetch(url, options))
.then(res => res.json() as Promise<T>);
if (!ignore) setData(response);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
})();
return (() => { ignore = true; });
}, [url, options, dependencies]);
return { data, loading, error };
}
Run Code Online (Sandbox Code Playgroud)
我发现如果我省略依赖项中的选项(这是有道理的,因为我们不希望这个深层对象以我们应该监视的方式改变)并传播传入的依赖项,它会按预期工作。当然,这两个变化都打破了“Hooks 规则”。
// Working - mad 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 ? fetch(url) : fetch(url, options))
.then(res => res.json() as Promise<T>);
if (!ignore) setData(response);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
})();
return (() => { ignore = true; });
}, [url, ...dependencies]);
return { data, loading, error };
}
Run Code Online (Sandbox Code Playgroud)
...然后我使用它
export const GetStuff: () => UseRequestResponse<Stuff[]> & { refresh: () => void } = () => {
const { appToken } = GetAppToken();
const [refreshIndex, setRefreshIndex] = useState(0);
return {
...UseRequest<Stuff[]>('https://my-domain.api/v1/stuff', {
method: 'GET',
headers: {
'Authorization': `Bearer ${appToken}`
}
}, [appToken, refreshIndex]),
refresh: () => setRefreshIndex(refreshIndex + 1),
};
};
Run Code Online (Sandbox Code Playgroud)
请注意,工作状态和损坏状态之间的唯一变化是:
}, [url, options, dependencies]);
Run Code Online (Sandbox Code Playgroud)
...到:
}, [url, ...dependencies]);
Run Code Online (Sandbox Code Playgroud)
那么,我怎么可能重写它以遵循 Hooks 规则而不陷入无限刷新循环?
以下是useRequest定义接口的完整代码:
import React, { useState, useEffect } from 'react';
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 ? fetch(url) : fetch(url, options))
.then(res => res.json() as Promise<T>);
if (!ignore) setData(response);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
})();
return (() => { ignore = true; });
}, [url, ...dependencies]);
return { data, loading, error };
}
export default UseRequest;
export interface UseRequestOptions {
method: string;
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
[prop: string]: string;
},
redirect: string, // manual, *follow, error
referrerPolicy: string, // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: string | { [prop: string]: any };
[prop: string]: any;
};
export interface UseRequestError {
message: string;
error: any;
code: string | number;
[prop: string]: any;
}
export interface UseRequestResponse<T> {
data: T | undefined;
loading: boolean;
error: Partial<UseRequestError> | undefined;
}
Run Code Online (Sandbox Code Playgroud)
那是因为您在每次渲染时都重新创建了一个新数组。事实上,整个依赖是没有意义的,因为你从来没有在效果中使用它。
您同样可以依赖选项对象,该对象具有不断变化的标题。但是由于对象也会在每次渲染时重新创建,因此您必须先记住它:
export const GetStuff: () => UseRequestResponse<Stuff[]> & { refresh: () => void } = () => {
const { appToken } = GetAppToken();
const [refreshIndex, setRefreshIndex] = useState(0);
const options = useMemo(() => ({
method: 'GET',
headers: {
'Authorization': `Bearer ${appToken}`
}
}), [appToken, refreshIndex])
return {
...UseRequest<Stuff[]>('https://my-domain.api/v1/stuff', options),
refresh: () => setRefreshIndex(refreshIndex + 1),
};
};
Run Code Online (Sandbox Code Playgroud)
然后,不是依赖刷新索引来触发刷新,您可以让useRequest()钩子返回一个刷新函数,该函数在内部也调用效果中的该函数(而不是将加载逻辑放在效果本身中,它只是调用该函数) . 通过这种方式,您可以更好地遵循规则,因为useMemo从不实际上依赖于刷新索引,因此它不应该在依赖项中。
| 归档时间: |
|
| 查看次数: |
338 次 |
| 最近记录: |