React Hook useEffect缺少依赖项 [英] React Hook useEffect has a missing dependency
问题描述
我在构建我的应用程序时遇到了问题.有人知道怎么了吗?
I am having this problem to build my app. Anyone knows what is wrong?
React Hook useEffect缺少依赖项:"conectar".要么包含它,要么删除依赖项数组react-hooks/exhaustive-deps
React Hook useEffect has a missing dependency: 'conectar'. Either include it or remove the dependency array react-hooks/exhaustive-deps
const GraficoEquivalenteNovo = props => {
const [equivalenteNovos, setEquivalenteNovos] = useState([]);
const [data, setData] = useState([]);
async function conectar() {
const resposta = await ConexaoGraficoEquivalenteNovo(props);
setEquivalenteNovos(resposta[0]);
setData(resposta[1]);
}
useEffect(() => {
conectar();
}, [props]);
return (....)
};
推荐答案
您的钩子取决于函数connectar
,该函数在钩子外部声明,但在渲染过程内部.在每个渲染器上都会对其进行重新制造.因此,React将其视为不稳定的依赖项.您可以在组件外部使用该函数,但是由于该函数本身使用状态挂钩并依赖于道具,因此请将其移到效果挂钩中.
Your hook depends on the function connectar
which is declared outside the hook, but is internal to the render process. It is re-manufactured on every render. Therefore, React sees it as a volatile dependency. You could have the function outside your component but since the function itself uses state hooks and depends on props, move it into the effect hook.
useEffect(() => {
async function conectar() {
const resposta = await ConexaoGraficoEquivalenteNovo(props);
setEquivalenteNovos(resposta[0]);
setData(resposta[1]);
}
conectar();
}, [props]);
这篇关于React Hook useEffect缺少依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!