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

自定义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

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

阅读 4.5k
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 , 里面该有的都有了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题