我正在研究 React 项目,并且正在研究一些库。我发现他们使用的“useCallback”与我使用的不同。下面是代码部分。我仍然认为这段代码与直接使用“useCallback”没有什么区别
// Saves incoming handler to the ref in order to avoid "useCallback hell"
export function useEventCallback<T, K>(handler?: (value: T, event: K) => void): (value: T, event: K) => void {
const callbackRef = useRef(handler);
useEffect(() => {
callbackRef.current = handler;
});
return useCallback((value: T, event: K) => callbackRef.current && callbackRef.current(value, event), []);
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是“useCallback hell”是什么意思?这样使用“useCallback”有什么好处?
// 顺便说一句:我在 React 文档中找到了类似的示例。但我仍然无法理解 https://en.reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
嗨,我正在学习 React,当我制作这个例子时,我感到有些好奇。这段代码就是向newsapi发送get请求,并接收结果。我使用了自定义钩子。
// *** this is where I use custom hook. "usePromise" is custom hook. *** //
function NewsList({ category }) {
const [loading, response, error] = usePromise(() => {
console.log("how many will it run?")
const query = category === 'all' ? '' : `&category=${category}`;
return axios.get(
`https://newsapi.org/v2/top-headlines?country=kr${query}&apiKey=044c3c345f28417380cd3ea946ac8641`
);
},[category]);
console.log(loading);
...
Run Code Online (Sandbox Code Playgroud)
我写了 console.log("how much will it run?") 来检查这个函数将运行多少个。还有console.log(loading)来检查加载将被更改的次数
// *** this is custom hook's code *** //
export default function usePromise(promiseCreator, deps) {
const [loading, setLoading] = …Run Code Online (Sandbox Code Playgroud)