useEffect中的数据初始化触发多个请求

IT技术 javascript reactjs
2021-05-22 07:33:27

这是一个后续问题这一个

简单地说,我以两种不同的方式获取相同的日期。一个一个,一起更新。我有一个带有上下文和useReducer.

我目前的代码是这样的:

import React, { useEffect } from "react";
import axios from "axios";
import { useGlobalState } from "./state";

const arr = Array.from(Array(100), (x, i) => i + 1);

function App() {
  const [{ posts, init }, dispatch] = useGlobalState();

  useEffect(() => {
    const getInc = () => {
      arr.forEach(async id => {
        const res = await axios(
          `https://jsonplaceholder.typicode.com/posts/${id}`
        );
        dispatch({
          type: "INC",
          payload: res.data
        });
      });
    };

    const getAll = async () => {
      const promises = arr.map(id =>
        axios(`https://jsonplaceholder.typicode.com/posts/${id}`)
      );
      const res = await Promise.all(promises);
      dispatch({
        type: "ALL",
        payload: res.map(el => el.data)
      });
    };

    if (init) {
      getInc();
    } else {
      getAll();
    }

    setInterval(() => getAll(), 10000);
  }, [dispatch, init]);

  return (
    <>
      <div>{posts.length}</div>
    </>
  );
}

export default App;

在每个间隔getAll被触发两次。是一个工作沙箱。

我添加了一个console.log减速器部分,所以你可以看到它运行了两次。我也可以在网络选项卡中看到它。

1个回答

使用时尝试单独关注useEffect,就像你提到的“一个一个一起更新”。

function App() {
  const [{ init, posts }, dispatch] = useGlobalState();

  useEffect(() => {
    setInterval(() => getAll(dispatch), 10000);
  }, [dispatch]);

  useEffect(() => {
    init ? getInc(dispatch) : getAll(dispatch);
  }, [init, dispatch]);
...
}

笔记:

  useEffect(() => {
    init ? getInc(dispatch) : getAll(dispatch);
  }, [init, dispatch]);

Afterinit变成truegetAll被调用两次,一次来自即将到来的interval,一次来自useEffect上面。

总而言之,在您的Network 上,带有 id 的前 3 个发布请求间隔[0-99]是:

  1. getInc
  2. getAlluseEffectinit
  3. getAllinterval

编辑有趣的紫罗兰色 pwew6