【发布时间】:2020-12-19 05:07:24
【问题描述】:
由于 eslint 的警告,我正在苦苦挣扎。
下面是示例代码,一旦我运行下面的代码,我就会从 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;
【问题讨论】:
-
把
maxId作为依赖....}, [pageNo, maxId]);否则maxId里面的效果可能不会改变,看看这个youtube.com/… -
@Niyas Nazar 谢谢。对我有很大帮助
标签: reactjs react-hooks