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

╄→гoц情女王★ 提交于 2021-01-28 13:33:42

问题


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..


回答1:


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>
  );
}


来源:https://stackoverflow.com/questions/61945129/how-can-i-receive-data-that-was-sent-by-express-on-functional-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!