函数调用时,React Hook useEffect缺少依赖项

时间:2020-08-31 04:16:55

标签: reactjs react-hooks

由于埃斯林特的警告,我很挣扎。

下面是示例代码,一旦运行下面的代码,我就会收到eslint的警告。

React Hook useEffect has a missing dependency: 'maxId'. Either include it or remove the dependency array.

如何删除警告?

我想让进程仅在pageNo和StartDate更改时才调用loadMapData函数。

示例代码;

import React, { useState, useEffect, useCallback } from "react";

const VehicleHistory = (props) => {
  //console.log("VehicleHistory");
  
  const pageSize = 10;

  const [mapData, setMapData] = useState();
  const [pageNo, setpageNo] = useState(1);
  const [startDate, setstartDate] = useState(100);
  const [maxId, setmaxId] = useState(0);

  useEffect(() => {
    console.log("useEffect.pageNo chainging====");

    
  const loadMapData = async () => {
    console.log('call loadMapData====');  
    try {
        //Api call to get list data
        //No meaning. Just for testing
        const _pageNo = pageNo;
        const _pageSize = pageSize
        const _maxId = maxId;
        setMapData('test'+_pageNo + _pageSize+_maxId);
        setmaxId(_pageNo + _pageSize);

    } catch (err) {
      console.log("err", err);
    }
  }

  
    loadMapData();
  }, [pageNo]);


  useEffect(() => {
    console.log("useEffect.startDate chainging====");
    setMapData(null);
    setpageNo(1);

  }, [startDate]);




  return (
    <div>
      <button onClick={e => setpageNo(p => p + 1)}>Change page</button>
      <button onClick={e => setstartDate(s => s + 1)}>Change date</button>
      
      <br />pageNo : {pageNo}
      <br />startdate : {startDate}
      <br />mapdata : {mapData}
    </div>
    
  );
};

export default VehicleHistory;

1 个答案:

答案 0 :(得分:0)

问题在此代码中。基本上在useEffect内部,您会期待maxId。您需要了解useEffect 的工作方式。 useEffect必需的依赖项数组,确保它们在这些值更改时都将运行。因此,您的情况maxId正在变化。 useEffect不确定那是为什么坚持给出错误的原因。

useEffect(() => {
    console.log("useEffect.pageNo chainging====");

    
  const loadMapData = async () => {
    console.log('call loadMapData====');  
    try {
        //Api call to get list data
        //No meaning. Just for testing
        const _pageNo = pageNo;
        const _pageSize = pageSize
        const _maxId = maxId; <- Issue is here
        setMapData('test'+_pageNo + _pageSize+_maxId);
        setmaxId(_pageNo + _pageSize);

    } catch (err) {
      console.log("err", err);
    }
  }

  
    loadMapData();
  }, [pageNo]);

解决方案:

useEffect(() => {
...code
},[pageNo,maxId]) <- add maxId in dependency array