undefined is not an object (evaluating 'this.props.navigation') react navigation

て烟熏妆下的殇ゞ 提交于 2020-01-05 05:33:08

问题


I'm using React Stack Navigator in React Native App. I have a problem with the navigation props.

Here is my component where I call my navigate method.

class CommandsList extends React.Component {
    constructor(props){
        super(props);
    }


    addCommand(){
        this.props.navigation.navigate("CreateCommand");
    }
    render() {
        return (
            <SafeAreaView style={{flex:1}}>
                <MyList itemsUrl="http://localhost:9000/commands"/>
                <Button title="Ajouter" onPress={this.addCommand}></Button>
            </SafeAreaView>
        );
    }
}

export default StackNavigator({
    CommandsList : {
        screen : CommandsList,
    },
});

And my App.js

const RootStack = StackNavigator(
    {
        CommandsList: {
            screen: CommandsList,
        },
        CreateCommand: {
            screen: CreateCommand,
        }
    },
    {
        initialRouteName: 'CommandsList'
    }
);

export default class App extends React.Component {
    render() {
        return <RootStack/>;
    }
}

I don't understand why I have an error on navigate methods. :/


回答1:


You need to bind your reference either using bind in the constructor or by using the fat arrow function to reference this to the context

addCommand = () => {
        this.props.navigation.navigate("CreateCommand");
}

or

constructor() {
   super()
   this.addCommand = this.addCommand.bind(this);
}

Also you may check this article



来源:https://stackoverflow.com/questions/49856497/undefined-is-not-an-object-evaluating-this-props-navigation-react-navigation

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