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

ぐ巨炮叔叔 提交于 2020-08-08 08:17:19

问题


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

回答1:


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;



回答2:


use props.route instead of props.navigation



来源:https://stackoverflow.com/questions/48919803/react-navigation-receiving-undefined-with-this-props-navigation-state-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!