Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Navigation: receiving 'undefined' with this.props.navigation.state.params

I have a strange problem when I am passing props down to another screen.

I am passing two parameters; title and body, to ArticleBody screen.

class ListButtonWrapper extends React.Component {
  constructor(props){
    super(props);
    this.articleSelected = this.articleSelected.bind(this);
  }

  articleSelected() {
    this.props.navigation.navigate('ArticleBody', {
      title: this.props.title,
      body: this.props.body
    });
  }

When the button is pressed, it should pass those props to the next screen. And it does!

class ArticleBody extends React.Component {
render() {

    const { params } = this.props.navigation.state;
    const { title } = params ? params.title : null;
    const { body } = params ? params.body : null;
    console.log(title, body, params.title, params.body);
    return (
      <View>
      <Text>Title: {title}</Text>
      <Text>Body: {body}</Text>
      </View>
    );

However, calling {title} or {body} in <Text> doesn't show anything. Using console.log reveals that {title} and {body} are undefined.

However! If I use params.title or params.body, both show up as they should. But, according to the documentation, calling title or body should work.

But, here's another problem. If I change const { title } = params ? params.title : null; to const { title } = params.title it still shows up as undefined when I call title

I'm stumped. So far I can call params.title or params.body directly, but it should be working in the defined variables as well, right?

What am I doing wrong?

UPDATE

Want to add a little update. If I console.log this.props.navigation.state, I see that the props are being passed down to ArticleBody. Here is the log:

{params: {…}, key: "id-1519274761934-2", routeName: "ArticleBody"}
key: "id-1519274761934-2"
params:
  body:"more stuff"
  title:"stuff"
__proto__
Object
routeName:"ArticleBody"
__proto__
Object
like image 786
Nathan Avatar asked Apr 13 '26 14:04

Nathan


1 Answers

The issue is with your code

const { title } = params ? params.title : null;
const { body } = params ? params.body : null;

The ternary condition is deciding which object you're trying to do a destructuring assignment on. In your case it's either the params.title or params.body. So your actually becomes

title = params.title.title
body = param.body.body

You should either use

const { title, body } = params ? params: null;

or

const title = params ? params.title: null;
const body = params ? params.body : null;
like image 178
Tarun Lalwani Avatar answered Apr 20 '26 18:04

Tarun Lalwani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!