我在功能组件中定义了useCallback函数,并在同一功能组件的useEffect中使用了它。在这种情况下,功能是否已优化?
import { useCallback, useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchMetadata } from '../features/metadata/metadataSlice';
import { getChangedItems } from '../app/evergreenAPI';
const useWatchChanges = () => {
const dispatch = useDispatch();
const { isLogged } = useSelector((state) => state.auth);
const handleChangedItems = useCallback((changedItems) => {
console.log('...doing something with', changedItems);
}, []);
const fetchChangedItems = async () => {
if (!isLogged) return false;
try {
const changedItems = await getChangedItems();
changedItems &&
setTimeout(() => {
handleChangedItems(changedItems);
});
fetchChangedItems();
} catch (e) {
console.log(e);
fetchChangedItems();
}
};
useEffect(() => {
fetchChangedItems();
}, [isLogged, fetchChangedItems]);
};
export default useWatchChanges;
答案 0 :(得分:0)
您在useCallback依赖项数组中缺少依赖项。
const handleChangedItems = useCallback((changedItems) => {
console.log('...doing something with', changedItems);
}, [changedItems]);
此外,在这里使用useCallback可能没有任何意义,因为useCallback还会占用执行时间和资源。但是由于执行时间/资源的限制,您的handleChangedItems不会执行任何值得放入useCallback的操作。请看一下: