焦点发生时如何在反应导航中重新渲染组件? [英] How to rerender a component in react-navigation when focus happen?
本文介绍了焦点发生时如何在反应导航中重新渲染组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我聚焦视图时,我正在尝试 useFocusEffect
在我的视图中重新渲染组件.
I am trying to useFocusEffect
to rerender a component in my view when I focus the view.
我做到了:
const [theKey, setTheKey] = useState(0);
那么:
useFocusEffect(() => { setTheKey(theKey + 1) }, [theKey]);
还有 jsx:
<SwipeListView key={theKey} />
效果不佳,出现错误:Maximum update depth exceeded
有人可以分享一种重新渲染的方法吗?
Can someone share a way to rerender it?
我的反应路由器没有这个问题.
I do not have this issue with react router.
推荐答案
问题在这里:
useFocusEffect(() => { setTheKey(theKey + 1) }, [theKey]);
在这个函数中你更新theKey
.每次 theKey
更新时,效果都会再次调用.这会导致无限循环.
Inside this function you update theKey
. And each time theKey
gets updated the effect gets called again. This results in an infinite loop.
有两种解决方案:
移除Key依赖:
useFocusEffect(
() => { setTheKey(theKey + 1) },
["replace with something else"]
);
在更新状态前添加条件:
Add a condition before updating the state:
useFocusEffect(
() => { if ("some condition") setTheKey(theKey + 1) },
[theKey]
);
这将防止无限循环.
这篇关于焦点发生时如何在反应导航中重新渲染组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文