[英]Where should I declare the useCallback function?. The function makes the dependencies of useEffect Hook change on every render
I was trying to add the async function in useEffect
.我试图在 useEffect 添加异步
useEffect
。 While doing this I am getting the warning about wrap fetchData
function in useCallback
hook.在执行此操作时,我收到有关在
useCallback
挂钩中 wrap fetchData
function 的警告。 So, Where should I declare the useCallback
function, and how to implement it?那么,应该在哪里声明
useCallback
function,如何实现呢?
Here is the code:这是代码:
import React, { useState, useEffect, useCallback } from 'react'
import './assets/main.css'
import ImageCard from './components/ImageCard'
import ImageSearch from './components/ImageSearch'
function App() {
const [images, setImages] = useState([])
const [isLoading, setIsLoading] = useState(true)
const [serachTerm, setSearchTerm] = useState('')
const fetchData = async () => {
try {
const data = await fetch(
`https://pixabay.com/api/?key=${process.env.REACT_APP_PIXABAY_API_KEY}&q=${serachTerm}&image_type=photo&pretty=true`
).then(res => res.json())
setImages(data.hits)
setIsLoading(false)
} catch (err) {
console.log(err)
}
}
useEffect(() => {
fetchData()
setIsLoading(false)
}, [setSearchTerm, fetchData])
The warning is about fetchData
being redeclared each render cycle, thus retriggering the useEffect
callback.警告是关于在每个渲染周期重新声明
fetchData
,从而重新触发useEffect
回调。 The useCallback
memoizes the function to provide a stable reference. useCallback
记忆 function 以提供稳定的参考。
You have two options:你有两个选择:
Memoize fetchData
with useCallback
使用 useCallback
fetchData
useCallback
const fetchData = useCallback(async () => {
try {
const data = await fetch(
`https://pixabay.com/api/?key=${process.env.REACT_APP_PIXABAY_API_KEY}&q=${serachTerm}&image_type=photo&pretty=true`
).then((res) => res.json());
setImages(data.hits);
} catch (err) {
console.log(err);
} finally {
setIsLoading(false); // <-- set loading false when done no matter what
}
}, [serachTerm]); // <-- add any missing dependencies react warns about
useEffect(() => {
fetchData();
setIsLoading(true); // <-- I think you meant for loading true
}, [setSearchTerm, fetchData]); // <-- double check setSearchTerm dependency
Move fetchData
into the useEffect
hook so its reference doesn't matter将
fetchData
移动到useEffect
挂钩中,因此它的引用无关紧要
useEffect(() => {
const fetchData = async () => {
try {
const data = await fetch(
`https://pixabay.com/api/?key=${process.env.REACT_APP_PIXABAY_API_KEY}&q=${serachTerm}&image_type=photo&pretty=true`
).then((res) => res.json());
setImages(data.hits);
} catch (err) {
console.log(err);
} finally {
setIsLoading(false);
}
};
fetchData();
setIsLoading(true);
}, [setSearchTerm]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.