React-native - 传递道具未定义

时间:2018-04-30 17:29:09

标签: javascript reactjs react-native

我正在尝试在两个文件之间传递用户名,但它仍未定义。我哪里错了?谢谢!

//登录文件

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

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


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

  }

在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

2 个答案:

答案 0 :(得分:0)

您正在主要组件中错误地访问参数,您需要从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);

答案 1 :(得分:0)

params时使用navigate()传递参数。

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

要使用this.props.navigation.state.params.username来访问它。

希望这会有所帮助!