同步 useEffect 请求

时间:2021-06-25 14:26:11

标签: reactjs use-effect

我有一个 useEffect 可以在页面加载时获取数据,并且我正在尝试在从初始调用的 JSON 对象接收到属性后立即添加另一个获取。有 2 个 useEffects 是一种很好的做法还是我应该换一种方式?

const [account, setAccount] = useState({});
const [billing, setBilling] = useState({});

useEffect(() => {
  const fetchAccountData = async () => {
    const rawRes = await fetch(`/customers/${customerId}`);
    const res = await rawRes.json();
    setAccount(res);
  };
  fetchAccountData();
}, []);

我试图让一个函数做一件事,所以我避免将第二个 useEffect 的函数添加到第一个。这是我的方法

useEffect(() => {
  const fetchAccountData = async () => {
    const rawRes = await fetch(`/customers/${customerId}`);
    const res = await rawRes.json();
    setAccount(res);
  };
  fetchAccountData();
}, []);

useEffect(() => {
  if (accountData.endDate) {
    const fetchBillingData = async () => {
      const rawRes = await fetch(`/customers/${customerId}/billing`);
      const res = await rawRes.json();
      setBilling(res);
    };
  fetchBillingData();
}, [accountData.endDate]);

1 个答案:

答案 0 :(得分:0)

你可以这样做,因为你的函数是异步的并且你正在使用await,这样写会达到你想要的结果:trying to add another fetch as soon as I receive a property from the initial call's JSON object

useEffect(() => {
  const fetchAccountData = async () => {
    const rawRes = await fetch(`/customers/${customerId}`);
    const res = await rawRes.json();
    setAccount(res);

    const rawRes2 = await fetch(`/customers/${customerId}/billing`);
    const res2 = await rawRes.json();
    setBilling(res2);
  };
  fetchAccountData();
}, []);