I am trying to pass a param from MenuScreen.js to the ProfileScreen.js. I am new to React Native and Redux. Using react-navigation for navigation, I am able to push to new screen with a button.
Using
Button onPress={() => dispatch(NavigationActions.navigate({ routeName: 'Profile', params: { user: 'baz' } }))} title="Profile" />
I am able to pass the params but I don't know how access it on the profile screen.
Using
this.props.navigation.state.params
in ProfileScreen.js is giving an error that
this.props.navigation
is undefined.
Below is the code,
MainScreen.js
const MainScreen = ({ dispatch }) => {
return (
<View>
<Button
onPress={() =>
dispatch(NavigationActions.navigate({ routeName: 'Profile', params: { user: 'baz' } }))}
title="Profile"
/>
</View>
);
};
MainScreen.propTypes = {
dispatch: PropTypes.func.isRequired,
};
MainScreen.navigationOptions = {
title: 'Main',
};
const mapStateToProps = state => ({
});
export default connect(mapStateToProps)(MainScreen);
ProfileScreen.js
const params = this.props.navigation.state.params;
const ProfileScreen = () => (
<View style={styles.container}>
<Text style={styles.welcome}>
{params}
</Text>
</View>
);
ProfileScreen.navigationOptions = {
title: 'Profile',
};
export default ProfileScreen;
index.reducer.js
import { AppNavigator } from '../navigators/AppNavigator';
const initialNavState = AppNavigator.router.getStateForAction(
AppNavigator.router.getActionForPathAndParams('Main')
);
function nav(state = initialNavState, action) {
let nextState;
switch (action.type) {
default:
nextState = AppNavigator.router.getStateForAction(action, state);
break;
}
return nextState || state;
}
const AppReducer = combineReducers({
nav,
});
export default AppReducer;
AppNavigator.js
import MainScreen from '../components/MainScreen';
import MainScreen from '../components/MainScreen';
import ProfileScreen from '../components/ProfileScreen';
export const AppNavigator = StackNavigator({
Main: { screen: MainScreen },
Profile: { screen: ProfileScreen },
});
const AppWithNavigationState = ({ dispatch, nav }) => (
<AppNavigator navigation={addNavigationHelpers({ dispatch, state:
nav })} />
);
AppWithNavigationState.propTypes = {
dispatch: PropTypes.func.isRequired,
nav: PropTypes.object.isRequired,
};
const mapStateToProps = state => ({
nav: state.nav,
});
export default connect(mapStateToProps)(AppWithNavigationState);
index.ios.js
class NavChecks extends React.Component {
store = createStore(AppReducer);
render() {
return (
<Provider store={this.store}>
<AppWithNavigationState />
</Provider>
);
}
}
AppRegistry.registerComponent('NavChecks', () => NavChecks);
export default NavChecks;
Try passing props to
ProfileScreen
: