React-hook-自定义hook

196 阅读1分钟
  1. 自定义一个简单的Axios请求的hook
  2. useAxios
  3. 要点:useState、useEffect、return [loading,data,error]
import axios from "axios";
import {useEffect, useState} from "react";

function useAxios(url){
    const [loading,setLoading] = useState(false)
    const [data,setData] = useState()
    const [error,setError] = useState()

    useEffect(()=>{
        setLoading(true)
        axios.get(url)
            .then(res => setData(res))
            .catch(e => setError(e))
            .finally(()=>setLoading(false))
    },[url])

    return [loading,data,error]
}

export default useAxios

使用

import React from "react";
import useAxios from "./hook04/useAxios";
function App(){
    const [loading,data,error] = useAxios('http://localhost:3002/')
    if (loading) return <div>loading ...</div>
    return <div>
            {error ? JSON.stringify(error) : JSON.stringify(data)}
        </div>
}

export default App