首页 > 解决方案 > 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.

标签: javascriptreact-nativeasync-awaitreact-navigationreact-navigation-v5

解决方案


我不认为你可以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()
}

推荐阅读