【发布时间】:2021-10-11 13:33:00
【问题描述】:
如何处理这个警告? (React Hook useMemo 缺少依赖项:'deleteTutorial' 和 'openTutorial'。要么包含它们,要么删除依赖数组 react-hooks/exhaustive-deps) 如果我将 openTutorial 和 deleteTutorial 放在 useMemo 钩子中,不会有编译警告,但是我有一个问题是这两个函数不起作用。
const openTutorial = (rowIndex) => {
const id = tutorialsRef.current[rowIndex].id;
props.history.push("/tutorials/" + id);
};
const deleteTutorial = (rowIndex) => {
const id = tutorialsRef.current[rowIndex].id;
TutorialDataService.remove(id).then((response) => {
props.history.push("/tutorials");
let newTutorials = [...tutorialsRef.current];
newTutorials.splice(rowIndex, 1);
setTutorials(newTutorials);
}).catch((e) => {
console.log(e);
});
};
const columns = useMemo(() => [
{
Header: "Naziv",
accessor: "title"
}, {
Header: "Opis",
accessor: "description"
}, {
Header: "Površina",
accessor: "povrsina"
}, {
Header: "Dužina x Širina",
accessor: properties => properties.duzina + ' x ' + properties.sirina
}, {
Header: "",
accessor: "actions",
Cell: (props) => {
const rowIdx = props.row.id;
return (<div>
<span onClick={() => openTutorial(rowIdx)}>
<i className="far fa-edit action mr-2"></i>
</span>
<span onClick={() => (confirmDialog('Da li želite obrisati parcelu?', () => deleteTutorial(rowIdx)))
}>
<i className="fas fa-trash action"></i>
</span>
</div>);
}
}
], []);
/编辑/ 现在我遇到了 useCallback 缺少依赖项 props.history 的问题。可以这样修复吗:
const callHistory = useCallback(() => {
props.history.push("/tutorials");
}, [props.history]);
const deleteTutorial = useCallback((rowIndex) => {
const id = tutorialsRef.current[rowIndex].id;
TutorialDataService.remove(id).then((response) => {
callHistory();
let newTutorials = [...tutorialsRef.current];
newTutorials.splice(rowIndex, 1);
setTutorials(newTutorials);
}).catch((e) => {
console.log(e);
});
}, [callHistory]);
【问题讨论】:
-
什么是“功能不起作用”?是用错误的数据调用“deleteTutorial()”还是根本不调用?你有没有在里面设置断点来检查发生了什么?
标签: reactjs react-hooks