停止 useEffect 在挂载上运行 [英] Stop useEffect from running on mount
问题描述
我只希望useEffect在我的依赖列表改变时运行,它也在每次挂载组件时运行,有什么办法不挂载时触发吗?
I only want useEffect to run when my dependency list changes, it is also running every time the component is mounted, is there any way to not fire on mount?
如果某些值,你可以告诉 React 跳过应用效果在重新渲染之间没有改变.
You can tell React to skip applying an effect if certain values haven’t changed between re-renders.
我最初认为这意味着它不应该在后续装载时重新渲染,但 这个问题澄清了这一点.
I initially thought that meant it shouldn't re-render on subsequent mounts but this question cleared that up.
我在主页面"(react-router)中显示记录列表,用户可以选择单个记录并转到详细信息页面,然后返回到主页面 - 所以主列表组件是在那种情况下完全卸载/安装.每次加载母版页"时,我都会看到正在获取的数据,我只希望在依赖项之一发生更改时发生这种情况;这些依赖项和数据本身都存储在 Redux 中,因此它们是全局的.
I am displaying a list of records in a master "page" (react-router), the user can choose a single record and go to the detail page, and then return to the master page - so the master list component is completely unmounted/mounted in that scenario. And every time I load the "master page", I see the data being fetched, I only want this to happen when one of the dependencies changes; these dependencies and the data itself are stored in Redux so they're global.
可以使 useEffect 或其他钩子仅在依赖项更改时触发吗?
Can useEffect or another hook be made to only fire when the dependencies change?
const {page, pageSize, search, sorts} = useSelector(getFilters);
const data = useSelector(getData);
useEffect(() => {
console.log("fetching");
dispatch(fetchData(page, pageSize, search, sorts));
}, [page, pageSize, search, sorts]);
推荐答案
你不能开箱即用地配置它.
You can't configure it out of the box.
但是,一个常见的模式是像这样使用一些 isMounted
标志:
But, a common pattern is to use some isMounted
flag like so:
// Is Mounted
const useFetchNotOnMount = () => {
...
const isMounted = useRef(false);
useEffect(() => {
if (isMounted.current) {
console.log('fetching');
dispatch(fetchData(filters));
} else {
isMounted.current = true;
}
}, [dispatch, filters]);
};
// Same (Is First Render)
const useFetchNotOnMount = () => {
...
const isFirstRender = useRef(true);
useEffect(() => {
if (isFirstRender.current) {
isFirstRender = false;
} else {
console.log("fetching");
dispatch(fetchData(filters));
}
}, [dispatch, filters]);
};
这篇关于停止 useEffect 在挂载上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!