我需要以兩種不同的方式獲取我的數(shù)據(jù)并根據(jù)此進(jìn)行渲染。在第一次加載時(shí),我需要一個(gè)一個(gè)地獲取所有項(xiàng)目并增加計(jì)數(shù)。之后,我需要一次獲取所有數(shù)據(jù)并更新顯示。所以,我寫了這樣的東西(不是實(shí)際的代碼,而是幾乎一樣的東西):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 }, 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 (!posts.length) { getInc(); } else { getAll(); } }, [dispatch]); return ( <> <div>{posts.length}</div> </> );}export default App;我只是在使用Context和useReducer創(chuàng)建一個(gè)簡單的商店。上面的代碼按原樣工作,但我跳過添加posts.length依賴項(xiàng),這讓我認(rèn)為我的邏輯是錯(cuò)誤的。我嘗試使用 refs 來跟蹤初始化狀態(tài),但我需要在每次路由更改時(shí)跟蹤數(shù)據(jù)。然后,我試圖通過向init我的商店添加一個(gè)狀態(tài)來保持它,但我無法讓它毫無問題地工作。例如,我找不到合適的地方發(fā)送init. 如果我在一次獲取后嘗試它,它會立即觸發(fā)初始化并getAll調(diào)用我的另一個(gè)函數(shù) ( )。如果有人想玩它,這里有一個(gè)工作沙箱:https : //codesandbox.io/s/great-monad-402lb
在相同的 useEffect 中依賴地使用相同的數(shù)據(jù)
千萬里不及你
2021-06-10 17:49:39