为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

明月笑刀无情 2021-06-15 09:08:46
简单地说,我以两种不同的方式获取相同的日期。一个一个,一起更新。我有一个带有上下文和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 回答

?
繁花不似锦

TA贡献1851条经验 获得超4个赞

使用时尝试单独关注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变成true,getAll被调用两次,一次来自即将到来的interval,一次来自useEffect上面。


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


  1. 从 getInc

  2. getAlluseEffectinit

  3. getAllinterval


查看完整回答
反对 回复 2021-06-18
  • 1 回答
  • 0 关注
  • 1052 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信