Home > Software design >  How to get params in React Navigation in class-based components?
How to get params in React Navigation in class-based components?

Time:09-19

Platform: React Native (Expo)

I want to get my params to a new screen using class-based components and React Navigation 6.0.

This is how I am sending the params:

this.props.navigation.navigate("BlogDetails", { blogID: item.ID });

and this is how I'm retrieving it:

componentDidMount() {
    const { blogID } = this.props.route.params;
    this.setState({ blobID: blogID });
    console.log(this.state.blobID);
  }

There are no errors, however, the console.log() returns "".

I am unable to find where I'm going wrong but I'm pretty sure the problem is somewhere during the retrieval, I'm pretty confident that the data is being sent to the screen.

CodePudding user response:

state doesn't update immediately, if you want use state after update should act like this

componentDidMount() {
 const { blogID } = this.props.route.params;
 this.setState({ blobID: blogID }, () => {
  console.log(this.state.blobID);
 });
}

CodePudding user response:

const {paramName1, paramName2, ...} = this.props.navigation.state.params

CodePudding user response:

It seems different for react navigation version.

const { blogID } = this.props.route.params;

or

const blogID = this.props.route.getParam('blogID);

try to use getParam function.

  • Related