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

前端 未结 13 2124
无人及你
无人及你 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:28

    You can remove the 2nd argument type array [] but the fetchBusinesses() will also be called every update. You can add an IF statement into the fetchBusinesses() implementation if you like.

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

    The other one is to implement the fetchBusinesses() function outside your component. Just don't forget to pass any dependency arguments to your fetchBusinesses(dependency) call, if any.

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

提交回复
热议问题