React Hook “useEffect” is called conditionally

后端 未结 4 2224
再見小時候
再見小時候 2020-12-15 04:53

React is complaining about code below, saying it useEffect is being called conditionally:

4条回答
  •  忘掉有多难
    2020-12-15 05:01

    I would argue there is a way to call hooks conditionally. You just have to export some members from that hook. Copy-paste this snippet in codesandbox:

    import React from "react";
    import ReactDOM from "react-dom";
    
    function useFetch() {
      return {
        todos: () =>
          fetch("https://jsonplaceholder.typicode.com/todos/1").then(response =>
            response.json()
          )
      };
    }
    
    const App = () => {
      const fetch = useFetch(); // get a reference to the hook
    
      if ("called conditionally") {
        fetch.todos().then(({title}) => 
          console.log("it works: ", title)); // it works:  delectus aut autem  
      }
    
      return null;
    };
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(, rootElement);
    

提交回复
热议问题