猿问

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

简单地说,我以两种不同的方式获取相同的日期。一个一个,一起更新。我有一个带有上下文和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减速器部分,所以你可以看到它运行了两次。我也可以在网络选项卡中看到它。


明月笑刀无情
浏览 1053回答 1
1回答

繁花不似锦

使用时尝试单独关注useEffect,就像你提到的“一个一个,一起更新”。function App() {&nbsp; const [{ init, posts }, dispatch] = useGlobalState();&nbsp; useEffect(() => {&nbsp; &nbsp; setInterval(() => getAll(dispatch), 10000);&nbsp; }, [dispatch]);&nbsp; useEffect(() => {&nbsp; &nbsp; init ? getInc(dispatch) : getAll(dispatch);&nbsp; }, [init, dispatch]);...}笔记:&nbsp; useEffect(() => {&nbsp; &nbsp; init ? getInc(dispatch) : getAll(dispatch);&nbsp; }, [init, dispatch]);Afterinit变成true,getAll被调用两次,一次来自即将到来的interval,一次来自useEffect上面。总而言之,在您的Network 上,带有 id 的前 3 个发布请求间隔[0-99]是:从&nbsp;getInc从getAll在useEffect与init从getAll在interval
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答