如何在使用react-native-navigation时显示组件时触发事件?

Dar*_*ryn 19 react-native react-native-navigation

我正在使用react-native与react-native-navigation.我想在显示组件时重新加载数据.当用户单击选项卡导航按钮时,将显示该组件.

我应该使用反应生命周期事件还是反应原生导航中的某些内容可以在用户导航回组件时触发功能?

我正在使用redux,我不确定是否可以用来帮助?

这个问题指的onDisplay是我正在寻找的东西.但是我找不到任何关于它的官方文档 - https://github.com/wix/react-native-navigation/issues/130

dct*_*ker 29

我喜欢Bruno Reis提出的解决方案.我调整了它以使它更简单.

class Whatever extends Component {
    componentDidMount(){
        this.load()
        this.props.navigation.addListener('willFocus', this.load)
    }
    load = () => {
        ...
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案提供了一个与react-navigation一起使用的解决方案,而不是OP所要求的react-native-navigation:/请参阅Stephen Liu和我的答案,了解RNN解决方案。 (4认同)

小智 7

文档中,它表明您可以添加一个焦点事件,如下所示:

import React, { useEffect } from 'react'

const MyComponent = ({ navigation }) => {

    useEffect(() => {
        const unsubscribe = navigation.addListener('focus', () => {
            // do something
            console.log('Hello World!')
        });
        return unsubscribe;
    }, [navigation]);

    return (
        <View>
            <Text>MyComponent</Text>
        </View>
    )
}

export default MyComponent
Run Code Online (Sandbox Code Playgroud)


Bru*_*eis 5

将此作为'callIfBackToThisRoute'...

export default ( props, call ) => {
    if( !props.navigation ) throw 'I need props.navigation'
    const thisRoute = props.navigation.state.routeName;
    props.navigation.addListener(
        'willFocus',
        payload => {
            if( payload.state.routeName == thisRoute) call(props)
        }
    );
}
Run Code Online (Sandbox Code Playgroud)

并在您的组件中使用它...

componentDidMount() {
    const { doIt } = this.props;
    doIt()
    callIfBackToThisRoute(
        this.props,
        (props) => doIt()
    )
}
Run Code Online (Sandbox Code Playgroud)