从屏幕返回时反应导航执行功能

时间:2018-06-27 14:19:11

标签: react-native react-navigation

我正在使用反应导航在屏幕之间导航。我有一个主屏幕(Main.js)和一个名为(Favorites.js)的屏幕。

我使用此功能转到我的收藏夹屏幕。

 _btnFavoritos = async () => {

    const movies = this.state.myFavorites;
    console.log("Abrir Favoritos");
    console.log(movies);
    this.props.navigation.navigate('screenFavoritos', { movies: movies });

};

怎么有回调函数,以便当我退出收藏夹屏幕并返回主屏幕时,触发能够更新主屏幕的功能?

1 个答案:

答案 0 :(得分:1)

没话题,但是我会从async中删除_btnFavoritos关键字,除非您的函数有更多需要它的代码并且您根本没有在此处添加它

解决方案:

 _btnFavoritos = () => {    
    const movies = this.state.myFavorites;
    console.log("Abrir Favoritos");
    console.log(movies);
    this.props.navigation.navigate('screenFavoritos',
            {
                    movies: movies,
                    updateMain: () => this.updateMain()
            });
};

updateMain = () => {
    // Sample update logic
    fetch('https://someEndpoint.com')
    .then(res => res.json())
    .then(json => this.setState({ movies: json })
    .catch(err => console.warn(err.message)
}

Favorites.js

componentWillUnmount(){
    const { params } = this.props.navigation.state
    params && params.updateMain && params.updateMain() // Checking that the function was passed down
                                               // as a navigation prop before executing
}