React-Navigation传递Props报错:Undefined 'this.props.navigation.state.props.p'
Hey there, let's fix this navigation parameter issue you're facing! The core mistake here is you're looking for the passed parameter in the wrong place within your UserArea component.
Why the error happens
When you pass parameters via navigate('UserArea', {p: 'Profile'}) in react-navigation, those values are stored in this.props.navigation.state.params, not this.props.navigation.state.props. That's why you're getting the "Undefined 'this.props.navigation.state.props.p'" error — that path simply doesn't exist.
Step 1: Fix the parameter retrieval in UserArea
Update your UserArea constructor to pull the parameter from the correct params object:
constructor(props) { super(props); this.state = { page: this.props.navigation.state.params.p, // Changed from props to params name: '', } }
Step 2: Fix the state update in componentDidMount
Also, there's a small mistake in how you're updating the name state later on. Directly mutating this.state (like this.state.name = user.displayName) won't trigger a component re-render. You should use this.setState() instead:
componentDidMount() { firebase.auth().onAuthStateChanged(user => { this.setState({name: user.displayName}); // Use setState here }) }
Modified UserArea component key parts
Here's how the corrected sections of your UserArea component will look:
export default class UserArea extends React.Component { static navigationOptions = { header: null, } constructor(props) { super(props); this.state = { page: this.props.navigation.state.params.p, name: '', } } componentWillMount(){ if (!firebase.apps.length) { firebase.initializeApp(config); } } componentDidMount() { firebase.auth().onAuthStateChanged(user => { this.setState({name: user.displayName}); }) } // ... rest of your render and tabbar code stays the same }
Extra tip
If you want to add a fallback value in case the parameter isn't passed (to avoid undefined errors), you can use optional chaining or a default value:
page: this.props.navigation.state.params?.p || 'Home'
This way, if p is missing, it'll default to 'Home' instead of throwing an error.
内容的提问来源于stack exchange,提问作者Cris Pop

