javascript - 发生焦点时如何在反应导航中重新渲染组件?
问题描述
useFocusEffect
当我聚焦视图时,我试图在我的视图中重新渲染一个组件。
我做了:
const [theKey, setTheKey] = useState(0);
然后:
useFocusEffect(() => { setTheKey(theKey + 1) }, [theKey]);
和 jsx:
<SwipeListView key={theKey} />
它不能很好地工作,我有错误:Maximum update depth exceeded
有人可以分享一种重新渲染它的方法吗?
我对反应路由器没有这个问题。
解决方案
问题在这里:
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]
);
这将防止无限循环。
推荐阅读
- ios - Xcode 11 (11A420a) 在使用 Command-Click 声明时不显示“嵌入 H/VStack”菜单项
- python - Mqtt 监听断开并自动重新连接
- c - 如何从内核空间重定向命令的标准输出
- python - 用列表理解理解函数
- javascript - 我需要帮助来修复表单中的空白电子邮件
- vue.js - Electron-Vue 应用程序的状态存储在哪里?
- c# - WCF 客户端 P12 证书问题 - 无法解析用于验证签名的 KeyInfo:KeyInfo 'SecurityKeyIdentifier'
- laravel - 如何使用 Datatables Yajra 在 Laravel 上下载文件
- javascript - 渲染进程的electron crashed事件触发太晚?
- c - 将字符串存储在 C 结构中