首页 > 解决方案 > 发生焦点时如何在反应导航中重新渲染组件?

问题描述

useFocusEffect当我聚焦视图时,我试图在我的视图中重新渲染一个组件。

我做了:

const [theKey, setTheKey] = useState(0);

然后:

useFocusEffect(() => { setTheKey(theKey + 1) }, [theKey]);

和 jsx:

<SwipeListView key={theKey} /> 

它不能很好地工作,我有错误:Maximum update depth exceeded

有人可以分享一种重新渲染它的方法吗?

我对反应路由器没有这个问题。

标签: javascriptreactjsreact-nativereact-navigationreact-navigation-v5

解决方案


问题在这里:

useFocusEffect(() => { setTheKey(theKey + 1) }, [theKey]);

在这个函数里面你更新theKey. 每次theKey更新时,效果都会再次被调用。这会导致无限循环。

有2个解决方案:

移除 Key 依赖:

useFocusEffect(
    () => { setTheKey(theKey + 1) }, 
    ["replace with something else"]
);

在更新状态之前添加一个条件:

useFocusEffect(
    () => { if ("some condition") setTheKey(theKey + 1) }, 
    [theKey]
);

这将防止无限循环。


推荐阅读