简单地说,我以两种不同的方式获取相同的日期。一个一个,一起更新。我有一个带有上下文和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]是:
从
getInc
从
getAll
在useEffect
与init
从
getAll
在interval
添加回答
举报
0/150
提交
取消