简体   繁体   English

通过导航传递状态时,this.props.navigation.state是未定义的吗?

[英]When passing state through navigation my this.props.navigation.state is undefined?

When I try to pass parameters through my navigation. 当我尝试通过导航传递参数时。 I can't seem to acces them. 我似乎无法接受他们。 They keep on beeing undefined when I try to use them. 当我尝试使用它们时,它们会保持不确定状态。

This is how I pass them: 这是我通过它们的方式:

this.props.navigation.navigate('gamescreen',{gameDTO:message.body})

This is how I try to use them: 这就是我尝试使用它们的方式:

renderChat() {
    console.log(this.props.navigation.state.params.gameDTO.gameId)
    return <Chat token={this.state.token} id={this.props.navigation.state.params.gameDTO.gameId}
                         name={this.state.username}/>
}

It keeps giving me TypeError: undefined is not an object (evaluating 'this.props.navigation.state') when I acces it. 当我访问它时,它一直给我TypeError:undefined不是对象(评估“ this.props.navigation.state”)。

However in my console.log, it is not undefined and just shows the right String. 但是在我的console.log中,它不是未定义的,只是显示正确的String。 Any ideas what I am doing wrong? 有什么想法我做错了吗? I'm fairly new to React Native. 我是React Native的新手。

As you can see, this is TypeError. 如您所见,这是TypeError。 this.props.navigation doesn't have state object, which means undefined object. this.props.navigation没有状态对象,这意味着未定义的对象。 Please refer to this link. 请参考此链接。 enter link description here 在此处输入链接说明

The renderChat() method must be declared in your component's constructor otherwise it will not have access to this . 必须在组件的constructor声明renderChat()方法,否则它将无法访问this

constructor(props){
 super(props)
 this.renderChat = this.renderChat.bind(this)
}

renderChat(){
   this.props.navigation.getParam('gameDTO', 'default') //returns id
}

Another solution is convert renderChat() into an arrow function 另一种解决方案是将renderChat()转换为箭头函数

renderChat = () => {
    this.props.navigation.getParam('gameDTO', 'default') //returns id
}

The problem was with the import of the chat component, that's why it could never recognize the navigation state. 问题在于聊天组件的导入,这就是为什么它永远无法识别导航状态的原因。 All the statements in this thread work fine for passing parameters through navigation. 该线程中的所有语句都可以很好地用于通过导航传递参数。 I just tab completed my Chat component and Webstorm didn't import the component from it's location, but imported it from a different screen I was using the component in. 我只是用Tab键完成了Chat组件,Webstorm并没有从其位置导入该组件,而是从我正在使用该组件的另一个屏幕中导入了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM