5

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);
};
Jude Fernandes
  • 7,437
  • 11
  • 53
  • 90

3 Answers3

12

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.

  • @BrunoMazzardo agreed, I should have mentioned I was looking for a more es6/ es7 way of doing it, if I don't receive any answers in a few days I will mark this as the correct one. – Jude Fernandes May 16 '18 at 16:43
  • If you want es7, then just do this in your class: state = { params: this.props.navigation.state.params } – Nathan Christian Jul 12 '18 at 18:53
  • Use getDerivedStateFromProps instead. Setting state from props in the constructor will cause bugs. Specially if you want to change state every time the prop changes. – Yasin Yaqoobi Oct 26 '18 at 02:36
0

Use componentWillMount, instead of navigationOptions

componentWillMount(){
   this.setState({
       params:this.props.navigation.state.params
       })
 }
Bruno Mazzardo
  • 1,586
  • 1
  • 15
  • 27
0

For anyone who is looking this is what I managed so far to get it working.

export default class Detail extends React.PureComponent {

state = {
    id: this.props.navigation.getParam('id', -1),
    title: this.props.navigation.getParam('title', null)
};

render() {

        return (

            . . .

        );
    }

}

This allows you to initialize the component with an initial state, might not be the best way and the code could definitely do with some destructuring but I'm not sure how to go about it so for now this works. Would love if someone could suggest a more efficient and performant way.

"dependencies": {
"react": "^16.3.1",
"react-native": "0.55.4",
"react-navigation": "^2.0.1"
}
Jude Fernandes
  • 7,437
  • 11
  • 53
  • 90