我正在嘗試實現一個鉤子 ( useFetch(route, dependencies=[])),它將用于fetch數據并返回一個標量值,loading用于確定用戶當前是否正在獲取新數據。這在初始渲染時按預期工作(因為默認狀態為loadingtrue)。每次后續渲染都會出現此問題。由于loading當前狀態設置為false(在初始渲染之后),loading狀態將在額外的渲染周期內保持 false 狀態,然后在useEffect().如何防止額外的loading=false渲染周期,以便我使用它的組件useFetch()立即意識到當前正在獲取數據并且我可以'...loading'在其中顯示文本render()(無需渲染兩次即可到達這一點)。使用獲取function useFetch(route, successHandler, dependencies = []) { const [loading, setLoading] = useState(true); useEffect(() => { setLoading(true); fetch(route, { method: 'POST', body: JSON.stringify({}), headers: {"Content-Type": "application/json"} }) .then(res => res.json()) .then( () => { // Set state data from component here successHandler(); }, () => {/*...*/}) .finally(() => { setLoading(false); }); }, dependencies); return loading;}成分function Component(){ const [toggle, setToggle] = useState(false); const [options, setOptions] = useState({}); const loading = useFetch('endpoint', () => setOptions({foo: 'bar'}), [toggle]); return <div> <button onClick={()=>{setToggle(!toggle)}}>Trigger useFetch()</button> {loading ? '...loading': options.foo} </div>;}任何幫助或設計建議將不勝感激,
React:實現一個鉤子來獲取數據并返回加載狀態
慕哥9229398
2021-10-14 15:43:30