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