今日已更新 166 条资讯 | 累计 20138 条内容
关于我们

From Axios to alova: how we cut 80 lines to 5

Scott Hu 2026年06月01日 11:35 6 次阅读 来源:Dev.to

Frontend request code often involves repetitive state management. This article compares Axios and alova through a paginated list example, analyzing how request strategization reduces boilerplate and when it's a good fit. The Pattern: Paginated List in Two Ways A common requirement: fetch a user list with pagination. Approach 1: Axios const [ data , setData ] = useState ([]); const [ page , setPage ] = useState ( 1 ); const [ total , setTotal ] = useState ( 0 ); const [ loading , setLoading ] = useState ( false ); const [ error , setError ] = useState ( null ); const fetchUsers = async ( currentPage ) => { setLoading ( true ); setError ( null ); try { const res = await axios . get ( ' /api/users ' , { params : { page : currentPage , pageSize : 10 }, }); setData ( res . data . list ); setTotal ( res . data . total ); } catch ( e ) { setError ( e . message ); } finally { setLoading ( false ); } }; useEffect (() => { fetchUsers ( page ); }, [ page ]); This pattern appears in nearly every data-fetching component. The actual business logic — GET /api/users — occupies a single line. The rest is infrastructure: state declarations, loading toggles, error handling, and effect management. Approach 2: alova with usePagination const { data , total , loading , error , page , pageSize , nextPage , prevPage , } = usePagination ( ( page , pageSize ) => alovaInstance . Get ( ' /api/users ' , { params : { page , pageSize }, }), { page : 1 , pageSize : 10 } ); Both implementations are functionally identical. The key difference is where the state management logic lives: in the component (Axios) vs. inside the hook (alova). What Changed Component of Axios version Handled by alova loading state + toggling Managed internally by usePagination error state + try/catch Managed internally by usePagination data state + assignment Returned as reactive value page state + change handler Built-in nextPage / prevPage total state extraction Extracted from response automatically useEffect dependency tr

本文内容来源于互联网,版权归原作者所有
查看原文