react中如何解决useEffect多次执行的问题?

125 阅读1分钟

1.添加依赖参数

useEffect(setup, dependencies?)

react会判断dependencies参数的值,如果一样就不会执行setup函数 ,否则每次页面渲染的执行一次

2. 返回要给清除函数

给fetch的api添加中断方法

return () => {
    const reason = new DOMException('message', 'AbortError');
    controller.abort(reason)
}

实例代码

import { useEffect, useState } from 'react'
function useFetchDate(url: string, optons: any = {}) {
    const [data, setData] = useState({})
    const [isPedding, setIsPedding] = useState(false)
    const [error, setError] = useState("");

    useEffect(() => {
        const controller = new AbortController();
        optons.signal  = controller.signal

        setIsPedding(false)
        fetch(url, optons).then((res) => {
            return res.json();
        }).then((res) => {
            setIsPedding(false)
            setData(res)
        }).catch((error) => {
            if (error instanceof DOMException && error.name === "AbortError") {
              console.log(error.message);
            } else {
              setError(error.message);
            }
          });

        return () => {
            const reason = new DOMException('message', 'AbortError');
            controller.abort(reason)
        }
    }, [url])

    return {
        data, 
        isPedding,
        error
    }
}

const App = () => {
    let [count, setCount] = useState(0)
    const clickHandle = () => {
        count++
        setCount(count)
    }
    const { data, isPedding } = useFetchDate('https://wangzhenhao.github.io/webpack-react-admin/data/user/getUserList.json', {
        methods: 'GET'
    })

    return ( <div>
        <h1>{count}</h1>
        <button onClick={clickHandle}>增加</button>
        { JSON.stringify(data) }
    </div> );
}
 
export default App;