javascript - Navigation addListener does not executes after await action
问题描述
I am listening to focus event on navigation in React native & using @react-navigation^5.x.x
in componentDidMount
. If only this action is written, then it works well and executes the code within it.
But in my case, I am fetching data from API (Also tried by mocking await) and using await before adding focus listener. It's not getting listened to for the first time. But when I go to another page and comes back, It starts working/executing.
Here's my code snippet.
async componentDidMount() {
await new Promise(resolve => setTimeout(resolve, 3000)); // 3 sec
navigation.addListener('focus', async (data) => {
console.log('This block not works for first time when I come on page.')
})
}
Edit - Even If I remove await and put the whole block in timeout, then also it stops executing the focus callback.
解决方案
我不认为你可以async
在生命周期中使用试试这个:
componentDidMount() {
const getData = async (params) => {
await new Promise(resolve => setTimeout(resolve, 3000)); // 3 sec
navigation.addListener('focus', async (data) => {
console.log('This block not works for first time when I come on page.')
})
}
getData()
}
推荐阅读
- laravel - Laravel Voyager 不显示图像
- reactjs - httpOnly cookie not getting sent with request from getInitialProps [Next.js]
- javascript - 是否有用于拆分字符串的正则表达式:“#CAT - meow meow #DOG - bark bark #FOX - 它说什么?” 在 #XXX 上同时保留 #XXX [在 Google 脚本中]?
- macos - How to use malloc in asm
- javascript - 如何在 gatsby 程序化导航中添加路由器转换?
- python - 返回 beta 系数 B0 和 B1 的函数
- visual-studio - 如何在 Visual Studio 2019 中覆盖 Vue.js 客户端脚本的源映射,以便调试器在断点处停止?
- winapi - 如何将 IMFSample 从 Windows Duplication API 编码为 H264?
- arduino - XMLHTTP --- ERR_CONNECTION_RESET
- javascript - 在 React 中显示单击元素的详细信息