简体   繁体   English

React-Native-传递道具未定义

[英]React-native - passing props undefined

I'm trying to pass a username between two files but it remains undefined. 我正在尝试在两个文件之间传递用户名,但该用户名仍未定义。 Where am I going wrong? 我要去哪里错了? Thanks! 谢谢!

//Login file //登录文件

      constructor(props){
        super(props);
        this.state={
          credentials: {
            username: "",
            password:"",

          }
        }
        this.navigate = this.props.navigation.navigate;
    }


      signIn(){
          {....}
          this.navigate("main", {
                username: this.state.username,
              });
        }

  }

In Main: 在主要:

constructor(props) {
        super(props);
    this.navigate = this.props.navigation.navigate;
    this.params = this.props.navigation.state.params;
}
{...}
    render() {
    console.log(this.params.username);
    //here it's undefined

You are accessing the params incorrectly in Main component, you need to access from this.props.navigation.state.params , you would get it like 您在Main组件中错误地访问了params,您需要从this.props.navigation.state.params进行访问,就像

constructor(props) {
        super(props);
    this.navigate = this.props.navigation.navigate;
    this.params = this.props.navigation.state.params;
}
{...}
render() {
console.log(this.props.navigation.state.params.username);

Use params while navigate() to pass the parameters. navigate()使用params传递参数。

this.navigate({
   routeName: 'main',
   key: 'main',
   params: { 
      username: this.state.username
   }
});

To access it use this.props.navigation.state.params.username . 要访问它,请使用this.props.navigation.state.params.username

Hope this will help! 希望这会有所帮助!

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

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