反应挂钩useEffect
在安装组件时运行。但是,如果效果依赖于用户输入,则效果的装载执行是多余的。那么可以对依赖项进行验证然后相应地执行钩子吗?
useEffect(() => {
const fetchDogImage = async () => {
const dogImage = await axios
.get(`https://dog.ceo/api/breed/${breed}/images/random`)
.then(response => response.data.message);
setDogImage(dogImage);
};
// This avoids fetching dog image on mount - user hasn't searched for a dog breed, yet.
// Is this an acceptable pattern?
if (breed !== '') {
fetchDogImage();
}
}, [breed]);
答案 0 :(得分:0)
是的,我认为可以进行检查以防止首次运行。此外,您也可以useDebouce避免过于频繁地进行搜索。例如
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(
() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
},
[value, delay],
);
return debouncedValue;
}
function App() {
const [dogImage, setDogImage] = useState('');
const [breed, setBreed] = useState('');
const debouncedValue = useDebounce(breed, 1000);
useEffect(() => {
const fetchDogImage = async () => {
const dogImage = await axios
.get(`https://dog.ceo/api/breed/${debouncedValue}/images/random`)
.then(response => response.data.message);
setDogImage(dogImage);
};
if (debouncedValue !== '') {
fetchDogImage();
}
}, [debouncedValue]);
return (
...
);
}