React Navigation Reset Can add parameters?

2019-06-28 06:36发布

问题:

I am still new to react navigation. I wish to reset the route information after login successfully. However there is some parameters like login information I wish to pass to the main page.

import { NavigationActions } from 'react-navigation'

const resetAction = NavigationActions.reset({
  index: 0,
  actions: [
        NavigationActions.navigate({ routeName: 'Profile',
                params:{user:this.state.username}})
      ]
  })
    this.props.navigation.dispatch(resetAction)

In the Profile page, I want to get access to the params, so I use this:

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

but I received: undefined is not an object (evaluating '_this.props.navigation.state.params.user') in the Console log. May I know how should I get the parameters? Thank you

回答1:

You can pass the params in reset action of react-native stack navigator like this:-

const resetAction = NavigationActions.reset({
            index: 0,
            actions: [ 
                NavigationActions.navigate({ 
                    routeName: 'ScreenName',      // name of the screen you want to navigate
                    params: {
                        paramsKey: paramsValue   // this second parameter is for sending the params
                    } 
                })
            ],
});
this.props.navigation.dispatch(resetAction);

And get the parameter value in second screen from the navigation state params like this:-

static navigationOptions = ({navigation, screenProps}) => {
    const params = navigation.state.params || {};   // You can get the params here as navigation.state.params.paramsKey

    console.log("CompareScreen product_id:", params.paramsKey);
}


回答2:

You are passing parameters by using username as key. So when you are retrieving it your code should look like this

Step 1: Pass params

this.props.navigation.navigate('Your-Screen_name',{ username: 'Lucy' })

Step2: Get Params

this.state = { 
    username: this.props.navigation.state.params.username, 
}


回答3:

This works for me:

  1. Pass param:

NavigationActions.navigate({ routeName: 'Location', params: { username: 'Luchi' }}),

  1. Get them:

const params = this.props.navigation.state.params || {}; if (!(params && params.username)) { alert('hi '+params.username) }