如何在打字稿中只调用一次函数

Oby*_*Pac 1 javascript typescript reactjs react-native expo

我一直在尝试开始使用 typescript 进行本地反应,但到目前为止并不容易,发现很难执行常见功能,例如在屏幕加载时获取 api,下面是当前正在使用的功能,但我不想使用超时加上它甚至无法正常工作(它必须等待我在运行之前设置的实际时间,这对 Android 不利),我只想在页面加载时调用该函数一次,我也尝试过使用 if else声明,但我不知道为什么它不仅仅适用于打字稿。

 (function(){  
   setTimeout(function () {
const newsUrl = 'http://172.20.10.4:8000/mobile/news';
    return fetch(newsUrl, {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
             'Cache-Control': 'no-cache'
          }
        })
        .then((response) => response.json())
        .then((data) => {
            let newArr = [...data];
            setProducts(newArr);
            //console.log(data);
            alert(38783763);
          
        })
        .catch((error) => {
            alert(error);
           console.error(error);
         });
       }, 200); 

}.call(this));
Run Code Online (Sandbox Code Playgroud)

axt*_*tck 5

您可以使用该useEffect钩子并在加载时传递一个空数组来获取数据。

useEffect(() => {
  fetch(newsUrl, {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
             'Cache-Control': 'no-cache'
          }
        })
        .then((response) => response.json())
        .then((data) => {
            let newArr = [...data];
            setProducts(newArr);
        })
}, []);
Run Code Online (Sandbox Code Playgroud)