How to fix missing dependency warning when using useEffect React Hook?

前端 未结 13 1832
无人及你
无人及你 2020-11-22 03:14

With React 16.8.6 (it was good on previous version 16.8.3), I get this error when I attempt to prevent an infinite loop on a fetch request

./src/components/Bu         


        
13条回答
  •  再見小時候
    2020-11-22 03:43

    you try this way

    const fetchBusinesses = () => {
        return fetch("theURL", {method: "GET"}
        )
          .then(res => normalizeResponseErrors(res))
          .then(res => {
            return res.json();
          })
          .then(rcvdBusinesses => {
            // some stuff
          })
          .catch(err => {
            // some error handling
          });
      };
    

    and

    useEffect(() => {
        fetchBusinesses();
      });
    

    it's work for you. But my suggestion is try this way also work for you. It's better than before way. I use this way:

    useEffect(() => {
            const fetchBusinesses = () => {
        return fetch("theURL", {method: "GET"}
        )
          .then(res => normalizeResponseErrors(res))
          .then(res => {
            return res.json();
          })
          .then(rcvdBusinesses => {
            // some stuff
          })
          .catch(err => {
            // some error handling
          });
      };
            fetchBusinesses();
          }, []);
    

    if you get data on the base of specific id then add in callback useEffect [id] then cannot show you warning React Hook useEffect has a missing dependency: 'any thing'. Either include it or remove the dependency array

提交回复
热议问题