我有一个与此非常相似的问题 -如何修复 React Hook useEffect 中缺少的依赖项 https://stackoverflow.com/questions/55840294/how-do-i-fix-missing-dependency-in-react-hook-useeffect.
有一个关键的区别 - 我将 fetch 函数传递给要从中调用的子组件使用效果 https://reactjs.org/docs/hooks-effect.html,所以我不能简单地将函数移动到效果主体中。每次渲染都会重新创建 fetch 函数并导致无限循环。我有其他本地组件状态,我想触发该效果。
我基本上有一个容器组件和一个演示组件。 MyPage 是 MyGrid 的父级并设置所有 redux 状态:
const MyPage = () => {
const dispatch = useDispatch();
const items= useSelector(selectors.getItems);
const fetching = useSelector(selectors.getFetching);
const fetchItems = opts => dispatch(actions.fetchItems(opts));
return (
<>
{fetching && <div>Loading...</div>}
<h1>Items</h1>
<MyGrid
items={items}
fetchItems={fetchItems}
fetching={fetching}
/>
</>
);
}
const MyGrid = ({ fetchItems, items, fetching }) => {
const [skip, setSkip] = useState(0);
const take = 100;
const [sorts, setSorts] = useState([]);
// when query opts change, get data
useEffect(() => {
const options = { skip, take };
const sortString = getSortString(sorts);
if (sortString) options['sort'] = sortString;
fetchItems(options);
}, [fetchItems, skip, sorts]);
在“MyGrid”中,“跳过”和“排序”可以更改,并且应该使效果生效。
“fetchItems”每次都会重新创建并导致无限循环。这
是我的问题。
现在,eslint react-hooks/exhaustive-deps 规则让我将 fetchItems 放入依赖项列表中。我有更漂亮的设置来在保存时自动修复,这使得情况变得更糟。
我知道容器/演示模式已经过时了,但它适合我的情况 - 我可能允许动态地将 MyGrid 替换为 MyList,并且不想在每个子组件中重复所有 redux 内容。
我尝试过了使用回调 https://reactjs.org/docs/hooks-reference.html#usecallback and useMemo https://reactjs.org/docs/hooks-reference.html#usememo,但 eslint 只是让我将所有相同的依赖项放入其依赖项数组参数中。
除了禁用 eslint 规则之外还有其他方法吗
// eslint-disable-next-line react-hooks/exhaustive-deps
使这项工作有效?