navigation.navigate is not a function

一曲冷凌霜 提交于 2019-12-24 11:27:44

问题


I'm using navigation to navigate my react native app and I couldn't Paypass this issue. I did as the docs but nothing works for me.

The problem is I'm trying to use the navigation option to add a header and right button to navigate me to another screen, but it keeps giving me this error: "navigation.navigate is not a function. (in navigation.navigate is undefined)

Here is my code:

    static navigationOptions = (navigation) => {
        return {
            title: 'Review Jobs',
            headerRight: (<Title onPress={()=>{navigation.navigate('settings')}}>Settings</Title>)
        };
    };

thank you


回答1:


This is a common problem with React, specially when you don't understand the newest JS standars (like ES6, that is used by React).

So, your problem is conceptual here. React components receive a single object, named props, that contains all the props. Normally, you use the deconstructing form to obtain directly some attributes of props. In this case, you want to have props.navigation.

You can deconstruct the props object in the arrow function arguments, that is what the documentation does, with ({navigation}) => ... instead of (navigation) => ...

That is the same as using (props) => ... and later do props.navegation

You will also need to change your onPress function. Using a {...} block in arrow function will not return anything unless you specify return. If you doesn't around your body function with {...}, then it is the same as writing { return ...}. So, if you want to return navigation.navigate('settings'), you have to delete the surrounding {...} or write return inside.

    static navigationOptions = ({navigation}) => {
        return {
            title: 'Review Jobs',
            headerRight: (<Title onPress={()=> navigation.navigate('settings')}>Settings</Title>)
        };
    };

Also, you could do the same with your navigationOptions function:

    static navigationOptions = ({navigation}) => ({
        title: 'Review Jobs',
        headerRight: (<Title onPress={() => navigation.navigate('settings')}> Settings </Title>),
    });



回答2:


use object destructuring while receiving the parameters as :

static navigationOptions = ({navigation}) => { // use {} to object destructuring
        return {
            title: 'Review Jobs',
            headerRight: (<Title onPress={()=>{navigation.navigate('settings')}}>Settings</Title>)
        };
    };


来源:https://stackoverflow.com/questions/52904853/navigation-navigate-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!