this.props.propsName引发未定义的错误

时间:2019-05-17 22:13:44

标签: react-native

在我的本机0.59应用程序中,当用户单击以下内容时就可以访问道具:

let obj = JSON.stringify({
        sender_id: this.props.user.id,
        event_id: this.props.eventId,
      });

此组件通过传递两个道具来调用:

this.props.navigation.navigate("Chat", {eventId: id, user: this.state.user});

但是会引发错误:

TypeError: undefined is not an object (evaluating 'this.props.user.id')

当我更改引用道具的方式时,它会起作用:

    sender_id: this.props.navigation.state.params.user.id,
    event_id: this.props.navigation.state.params.eventId,

但是react native doc使用this.props.props_name来访问组件的道具。哪一个是正确的?

2 个答案:

答案 0 :(得分:1)

看看反应导航网站https://reactnavigation.org/docs/en/params.html

似乎您应该执行以下操作:

const { navigation } = this.props;
const eventId= navigation.getParam('eventId', 'NO-ID');
const user= navigation.getParam('user', 'some default value');

希望对您有帮助。

答案 1 :(得分:1)

第二个选项正确,因为您正在导航上传递只能通过导航状态访问的参数。 如下:

sender_id: this.props.navigation.state.params.user.id, 
event_id: this.props.navigation.state.params.eventId

或者您可以使用getParam函数来传递2个参数 作为字符串 参数的默认值

sender_id: this.props.navigation.getParam('user', {id: undefined}).id, 
event_id: this.props.navigation.getParam('eventId', undefined)

有关更多详细信息,请访问react navigation