简体   繁体   English

我应该在哪里声明 useCallback function? function 使 useEffect Hook 的依赖关系在每次渲染时都发生变化

[英]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 matterfetchData移动到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.

相关问题 &#39;refreshToken&#39; 函数使 useEffect Hook(第 142 行)的依赖关系在每次渲染时都发生变化 - The 'refreshToken' function makes the dependencies of useEffect Hook (at line 142) change on every render 如何修复警告“function — 使 useEffect Hook 的依赖项在每次渲染时都发生变化”? - How to fix warning “function — makes the dependencies of useEffect Hook change on every render”? 我应该在哪里声明在useEffect()挂钩内调用的函数? - Where should I declare functions that are called inside a useEffect() hook? 我应该将此 function 包装在 useCallback 中吗? - Should I wrap this function in a useCallback? Should we use useCallback in every function handler in React Functional Components - Should we use useCallback in every function handler in React Functional Components 每次渲染时都将不同的 function 传递给 useEffect? - ReactJS 使用效果 - Different function gets passed to useEffect on every render? - ReactJS useEffect React Hook useCallback 收到一个依赖未知的函数。 改为传递内联函数 - React Hook useCallback received a function whose dependencies are unknown. Pass an inline function instead 使用带有依赖项的 useEffect 钩子时,清理功能何时触发? - When is the cleanup function triggered when using useEffect hook with dependencies? React useEffect Hook 不会在具有 [] 依赖项的第一次渲染时触发 - React useEffect Hook not Triggering on First Render with [] Dependencies 关于 useCallback hook 和匿名函数的问题 - Questions about useCallback hook and anonymous function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM