向React挂钩添加依赖项会导致无限循环

时间:2020-01-02 19:09:42

标签: reactjs react-hooks

我正在尝试使用从父级组件收到的道具来更新状态。

但是当我希望效果仅在组件安装时运行一次时,react会继续发出警告消息以将正在更新的状态添加到依赖项列表中。

以下是引发警告消息的组件的代码:

    router.post("/upload",upload.single('file'), async (req,res)=>{ 
  if(req.file){
    var headers = {
        headers: {"Authorization" : `Bearer ${config.access_token_imgur}`, 'content-type': 'multipart/form-data'}
    };
    var formData = new FormData();
    //formData.append("image", req.file);
    axios.post('https://api.imgur.com/3/upload', formData, headers).then((res)=>{
        console.log(res);
        console.log(res.body);
        console.log(res.data);
    }).catch((error)=>{
        console.log(error);
    })

    //must get a picture from the parameters (how to handle ? )
    //send it to https://api.imgur.com/3/upload with headers with post method
    //handle response
  }else{
      res.status(500).json({success: false})
  }

运行上述代码后,它可以正常工作,但始终会发出以下警告。

React Hook useEffect缺少依赖项:“ disableDate”和 “广告位”。包括它们或删除依赖项数组。您可以 如果您只执行功能更新'setDisableDate(d => ...)' 在“ setDisableDate”调用中需要“ disableDate” 反应钩/详尽的下降

如何解决此问题?

2 个答案:

答案 0 :(得分:0)

您可以通过在依赖项数组之前添加// eslint-disable-next-line react-hooks/exhaustive-deps行来禁用该警告消息。这样,useEffect回调仍将仅触发一次,但您不会在同一时间看到警告消息。

就像下面这样:

useEffect(() => {
  // ... your code

// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

我希望这会有所帮助!

答案 1 :(得分:0)

在两次setDisableDate通话中都尝试使用functional update,如警告所示:

setDisableDate(prevDisableDate => [
   ...prevDisableDate,
   {
     before: new Date(key[0]),
     after: new Date(key[key.length - 1])
   }
]);
setDisableDate(prevDisableDate => [...prevDisableDate, new Date(date)]);

那样,disableDate不会在useEffect内部使用,也不需要在依赖项数组上添加它。