简体   繁体   中英

How can I receive data that was sent by express on functional component?

function Header(props) {  
  const [ serverData, setServerData ] = useState({});

  fetch('http://localhost:4001/api')
      .then(res => res.json())
      .then((data) => {
        setServerData(data);
        console.log(data);
      });

  return (
      <div>{serverData}</div>
  );
}

I'm trying to make this functional React component to get data from express api.

My code editor keep shutting down, I think that receiving data part is in the loop.

How can I make this functional component to fetch the data just once, without using componentdidmount or class type component.

I tried useCallback, it did not work for me..

Use useEffect hook if you want to do this. If will happen once unless the dependencies change (no dependencies listed here).

function Header(props) {  
  const [ serverData, setServerData ] = useState({});

  useEffect(() => {
    fetch('http://localhost:4001/api')
      .then(res => res.json())
      .then((data) => {
        setServerData(data);
        console.log(data);
      });
  }, []);

  return (
      <div>{serverData}</div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM