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