Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set initial state from navigation props

I am using React Navigation to route between screen. I have an initial screen which contains a FlatList, onclick of an item I route to a new screen while passing params like this.

props.navigation.navigate('Details', {
    id: props.id,
    title: props.title
});

In the Details screen I can receive it using the following code but how do I set the state considering it's a static function and I do not have access to this.setState().

static navigationOptions = ({navigation}) => {
    const {params} = navigation.state;

    console.log(params);
};
like image 925
Jude Fernandes Avatar asked May 16 '18 13:05

Jude Fernandes


1 Answers

This will allow you to handle it in the constructor, which is the other location anything that used to be placed in componentWillMount can go.

constructor(props) {
    super(props)
    this.state = {
        params: props.navigation.state.params
    }
}

For reference, by passing in the props as an argument to constructor and then running the super function on them, you gain the ability to set your initial state or run other one-time functions before any other life-cycle functions are called.

like image 140
Nathan Christian Avatar answered Sep 21 '22 21:09

Nathan Christian