React hook 自定义传入依赖react-hooks/exhaustive-deps报warning

Teamo丶z
  • 2
新手上路,请多包涵

自定义url请求hook,deps为依赖项,拼接到useEffect的依赖项,报warning;

const useURLLoader = (url: string, deps: any[] = []) => {
    const [ data, setData ] = useState<any>(null)
    const [ loading, setLoading ] = useState(false)
    useEffect(() => {
        setLoading(true)
        axios.get(url).then(
            res => {
                setData(res.data)
                setLoading(false)
            }
        )
    }, [url, ...deps])
    return [ data, loading ]
}

warning:React Hook useEffect has a spread element in its dependency array. This means we can't statically verify whether you've passed the correct dependencies react-hooks/exhaustive-deps

请问,我怎么处理可以避过这个检测?

回复
阅读 69
1 个回答

使用 // eslint-disable-next-line react-hooks/exhaustive-deps 禁用该规则即可. 如下:

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [url, ...deps])
return [ data, loading ]

另外你可以不用自己实现这个hook, 可以使用阿里的 ahooks#useRequest , 里面该有的都有了

你知道吗?

宣传栏