1

我试图在useEffect. 在执行此操作时,我收到有关钩子中的 wrapfetchData函数的警告。useCallback那么,我应该在哪里声明useCallback函数,以及如何实现呢?

这是代码:

    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])

4

1 回答 1

1

警告是关于fetchData在每个渲染周期重新声明,从而重新触发useEffect回调。useCallback记忆功能提供一个稳定的参考。

你有两个选择:

记忆fetchDatauseCallback

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

移动fetchDatauseEffect钩子中,这样它的引用就无关紧要了

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]);
于 2020-11-26T07:40:56.017 回答