javascript 在React Native中加载下一个组件之前需要等待一定的时间

s5a0g9ez  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(81)

我的API密钥限制我在5秒内发出超过1个请求,所以我想在发出另一个NearbyJobs请求之前等待5秒(第一个请求是PopularJobs)。

<ScrollView showsVerticalScrollIndicator={false} horizontal={false}>   
    <View style={{ flex: 1, padding: SIZES.medium }}>
      <Welcome />
      <Popularjobs />
      {/* {setTimeout(() => {}, 6000)} */}
      <Nearbyjobs />
    </View>
</ScrollView>

API调用

import { useState, useEffect } from "react";
import axios from "axios";
const useFetch = (endpoint, query) => {
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const options = {
    method: "GET",
    url: `https://jsearch.p.rapidapi.com/${endpoint}`,
    params: { ...query },
    headers: {
      "X-RapidAPI-Key": "",
      "X-RapidAPI-Host": "jsearch.p.rapidapi.com",
    },
  };
  const fetchData = async () => {
    setLoading(true);
    try {
      const response = await axios.request(options);
      setData(response.data.data);
    } catch (err) {
      setError(err);
      alert(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const refetch = () => {
    setLoading(true);
    fetchData();
  };
  return { data, error, loading, refetch };
};
export default useFetch;
7gyucuyw

7gyucuyw1#

你能尝试在useEffect中使用setTimeout吗?

useEffect(() => {
  fetchData();

  const timeout = setTimeout(() => {
    fetchData();
  }, 6000);
  return () => clearTimeout(timeout);
}, []);

相关问题