• hook函数之useEffect的使用——自定义hook函数网络请求——


    hook函数之useEffect的使用


    此hook可以模拟函数组件的生命周期,函数组件对于在一些生命周期中操作还是无能为力,所以 React提供了 useEffect 来帮助开发者处理函数组件,来帮助模拟完成一部份的开发中非常常用的生命周期方法。常被别的称为:副作用处理函数。此函数的操作是异步的。

    • 注:useEffect中不能有返回值,React它要自动回收

    模拟的生命周期就有三个:

    useEffect副作用函数  它可以让函数组件中模拟生命周期
    生命周期 componentDidMount componentDidUpdate componentWillUnmout
    
    • 1
    • 2

    原理:

    []记录下来
    [] => []  所有值比对,如果值没有变化则不执行,有变化执行
    arguments.length
    deparr undefined 没有第2
    • 1
    • 2
    • 3
    • 4

    模拟 componentDidMount , componentWillUnmout

    useEffect(()=>{
        console.log("App");
    })
    
    • 1
    • 2
    • 3

    模拟挂载 componentDidMount

    参数2:依赖项,如果为空数组,则只执行1次
    一般在这样的写法中,完成网络请求

    useEffect(()=>{
        console.log("App");
    },[])
    
    • 1
    • 2
    • 3

    模拟更新 componentDidUpdate

    只针对某个数据count的值来做更新周期的检测
    useEffect(()=>{
        console.log("App");
    },[count])
    
    • 1
    • 2
    • 3
    • 4

    模拟卸载 componentWillUnmout

    有依赖项,数据更新就卸载原来的,重新渲染页面

    useEffect(()=>{
        console.log("App");
    },[count])
    
    • 1
    • 2
    • 3
    const Child = () => {
        useEffect(() => {
            return () => {
                console.log("child_____componentWillUnmout");
            }
        }, [])
        return (
            <div>
                <h2>Child</h2>
            </div>
        )
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    useEffect 网络请求

    • 在之前的版本:第1个参数要求只能是一个普通的函数,没有返回对象,可以返回回调函数,回调函数它模拟生命周期componentWillUnmout
    • 在代码中,我们使用async / await从第三方API获取数据。如果你对async/await熟悉的话,你会知道,每个async函数都会默认返回一个隐式的promise。但是,useEffect不应该返回任何内容。这就是为什么会在控制台日志中看到以下警告:
    • Warning: useEffect function must return a cleanup function or nothing. Promises and useEffect(async () => …) are not supported, but you can call an async function inside an effect

    最新的写法

    useEffect(async () => {
       let ret = await get('/api/swiper')
       setFilms(ret.data)
     }, [])
    
    • 1
    • 2
    • 3
    • 4

    版本普世的写法,利用一个自执行的函数;
    如果useEffect顶层不支持 async/await可以使用如下的解决方案

        useEffect(()=>{
            (async function(){
                let ret = await get("/api/swiper");
                setFime(ret.data)
                console.log(ret.data);
            })()
        },[])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    自定义hook函数网络请求

    import { get } from '@/utils/http';
    import { useState, useEffect } from 'react';
    
    const useSwiper = (initState = [])=>{
        let [fime,setFime] = useState(initState);
    
        useEffect(()=>{
            (async function(){
                let ret = await get("/api/swiper");
                setFime(ret.data)
            })()
        },[])
    
        return fime
    }
    
    export default useSwiper;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    把函数也传出去,完成对useEffect的操作

    使用闭包的原理,操作了原来函数中的数据

    import { get } from '@/utils/http';
    import { useState, useEffect } from 'react';
    
    const useGoodFood = (initState = [])=>{
        let [data,setData] = useState(initState);
        let [page,setPage] = useState(1);
    
        const loadData = async ()=>{
            let ret =await get("/api/goodfood?page="+page);
            if(ret.data.length>0){
                // setData(ret.data)
                setData(v=>[...v,...ret.data])
                setPage(v=>v+1)
            }
        }
        useEffect(()=>{
            loadData()
        },[])
    
        return [data,loadData]
    }
    
    export default useGoodFood;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    import useForm from "@/hook/useGoodFood.js"
    const App = () => {
        let [fime,loadData] = useForm()
        console.log(fime);
        return (
            <div>
                <ul>
                    {fime.map(({name,id})=><li key={id}>{name}</li>)}
                </ul>
                <button onClick={()=>loadData(2)}>下一页</button>
            </div>
        );
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  • 相关阅读:
    思腾云计算
    北邮22级信通院数电:Verilog-FPGA(7)第七周实验(2):BCD七段显示译码器(关注我的uu们加群咯~)
    linux-动态库和静态库制作和使用
    011python-if判断语句使用
    vue中省市区
    Pytorch之ResNet图像分类
    代码随想录算法训练营第五十天 |123.买卖股票的最佳时机III、188.买卖股票的最佳时机IV
    Intel announces Arc Pro A40 and Arc A50 professional desktop GPUs【外媒芯片报道(手工翻译)】
    第五章 将对象映射到 XML - 指定映射 XML 文档的格式选项
    SpringCloud(35):Nacos 服务发现快速入门
  • 原文地址:https://blog.csdn.net/m0_46672781/article/details/127132838