【问题标题】:React navigation without navigation prop, 'dispatch undefined'没有导航道具的反应导航,'dispatch undefined'
【发布时间】:2019-05-25 08:39:36
【问题描述】:

在我的应用程序中,我使用 React-Navigation 设置了导航,没有像这样的导航道具:https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html

但是,当我尝试拨打 NavigationService.navigate('LoginScreen');componentDidMount() 我得到'dispatch undefined'。

当我从render() 内部的onTap 调用相同的函数时,我按预期导航。

代码:

class SplashScreen extends Component {

    componentDidMount() {
        NavigationService.navigate('LoginScreen'); // does not work
    }
    //works at "onPress"
    render() {
        return (
            <View style={styles.container}>
                <Text onPress={() => NavigationService.navigate('LoginScreen')}>SplashScreen</Text>
            </View>
        );
    }
}

关于如何解决这个问题的任何想法?

【问题讨论】:

    标签: react-native react-native-navigation


    【解决方案1】:

    您可以使用withNavigation。像这样:

    import {withNavigation} from 'react-navigation'
    class SplashScreen extends Component {
    
        componentDidMount = () => {
            this.props.navigation.navigate('LoginScreen'); // Change it
        }
    
        render() {
            return (
                <View style={styles.container}>
                    <Text onPress={() => this.props.navigation.navigate('LoginScreen')}>SplashScreen</Text>
                </View>
            )
        }
    }
    
    export default withNavigation(SplashScreen) // export component like this
    

    withNavigationHOCreact-navigation 库提供的,它包装您的组件以传递所需的 navigation 属性。

    【讨论】:

      猜你喜欢
      • 2020-04-07
      • 2021-06-13
      • 2019-07-01
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      • 2020-05-29
      • 1970-01-01
      相关资源
      最近更新 更多