【问题标题】:react-hooks/exhaustive-deps warningreact-hooks/exhaustive-deps 警告
【发布时间】:2020-05-01 13:06:12
【问题描述】:

我使用 react hook useEffect 像下面的代码来获取数据并更改其中的状态。为了避免无限循环,我添加了一个空数组作为 useEffect 的第二个参数,我收到了这个警告。我只是忽略它还是我必须修复它?如果是这样,如何解决?我这里只想要componentDidMount 效果。 我很感激任何想法?

useEffect(() => {
 fetch('/login')
 .then(response => {
   if (response.ok) fetchAll() 
   else setLoading({ ...loading, signin: true, progress:false });     
 }).catch(() =>{
   setLoading({ ...loading, signin: true, progress:false });
 })
},[]);

【问题讨论】:

  • 您收到什么警告?你能提供所有要复制的代码吗?
  • 这就是我得到的React Hook useEffect has missing dependencies: 'fetchAll' and 'loading'. Either include them or remove the dependency array. You can also do a functional update 'setLoading(l => ...)' if you only need 'loading' in the 'setLoading' call react-hooks/exhaustive-deps@PiotrŻak
  • 尝试传递给 useEffect fetchAll & loading
  • useEffect((fetchAll, loading) => {

标签: reactjs react-hooks eslint


【解决方案1】:

试试这个,这应该可以解决警告

useEffect(() => {
 fetch('/login')
 .then(response => {
   if (response.ok) fetchAll() 
   else setLoading(loading => ({ ...loading, signin: true, progress:false }));     
 }).catch(() =>{
   setLoading(loading => ({ ...loading, signin: true, progress:false }));
 })
},[]);

【讨论】:

    猜你喜欢
    • 2021-04-15
    • 2020-01-18
    • 2021-09-03
    • 1970-01-01
    • 2021-02-18
    • 2020-06-22
    • 2020-02-21
    • 2020-06-08
    • 2020-10-12
    相关资源
    最近更新 更多