React-native检查我的参数是否未定义

时间:2017-10-23 13:22:11

标签: react-native parameters undefined

我正在寻找一种方法来检查我的参数是否未定义。 我尝试了但它不起作用:

componentWillMount() {
    if (typeof this.props.navigation.state.params.Username != 'undefined'){
        this.getInfos()
    } else {
        this.navigate('ComponentOne');
    }
}

仍有此错误:“undefined不是对象(评估'this.props.navigation.state.params.Username')”

有什么想法吗?

由于

2 个答案:

答案 0 :(得分:2)

尝试使用componentDidMount()而不是componentWillMount()

componentDidMount() {
  if (this.props.navigation.state.params.Username){
        this.getInfos()
    } else {
        this.navigate('ComponentOne');
    }
}

如果仍然存在,您将收到此未定义的错误,那么您的“#params'必须自己未定义。您不能在未定义的

上使用点运算符
console.log(this.props.navigation.state.params)

检查它是否未定义并调试你的错误

答案 1 :(得分:0)

试试这个:

if (this.props.navigation.state.params.Username) {
    this.getInfos()
}

或用双引号替换单引号(在Reactjs中测试):

if (typeof this.props.navigation.state.params.Username != "undefined") {
     this.getInfos()
}