2016-08-29 6 views
1

私はAPIへの小さなログインを持っているので、ログインがうまくいかなかった場合、警告メッセージが表示されます。しかし、私が良いユーザーを渡しているとき、エラーオブジェクトres.errors [0]が定義されていないことがわかりました(これは当然です)。このコードをリメイクして両方で動作させる良い方法は何ですか?ここでReact-Native:オブジェクトが定義されていない場合にifステートメントを渡す

は私のコードです:

LoginAPI.getToken(this.state.value) 
     .then((res) => { 
      if (typeof res.errors[0] !== 'undefined') { 
       if (res.errors[0].code === 'auth.credentials') { 
        this.setState({ 
         error: 'Username or Password are incorrect!', 
         isLoading: false, 
         token: null 
        }); 
        Alert.alert(
         'Login', 
         this.state.error 
        ) 
       } 
      } 
      else { 
       this.setState({ token: res }); 
       LoginAPI.getUser(this.state.token) 
        .then((res) => { 
         Actions.dashboard({userData: res}); 
        }); 
       this.setState({ 
        isLoading: false 
       }); 
      } 
     }).catch((error) => { 
      console.error(error); 
     }); 

はお時間をいただき、ありがとうございます!

答えて

2

オブジェクトまたは配列のネストされた値をチェックするときは、このようにチェックする必要があります。

if (res && res.errors && res.errors[0] && res.errors[0].code === 'auth.credentials') {

ほとんどの場合、それは未定義のオブジェクトのプロパティのプロパティを読み取ろうとすると、JavaScriptのだがそのようではないを行います。だから、あなたのロジックはこれ以上のように見えます。

LoginAPI.getToken(this.state.value) 
     .then((res) => { 
      if (res && res.errors && res.errors[0] && res.errors[0].code === 'auth.credentials') { 
       this.setState({ 
        error: 'Username or Password are incorrect!', 
        isLoading: false, 
        token: null 
       }); 
       Alert.alert(
        'Login', 
        this.state.error 
       ) 
      } 
      else { 
       this.setState({ token: res }); 
       LoginAPI.getUser(this.state.token) 
        .then((res) => { 
         Actions.dashboard({userData: res}); 
        }); 
       this.setState({ 
        isLoading: false 
       }); 
      } 
     }).catch((error) => { 
      console.error(error); 
     }); 
+0

本当にありがとうございました!私は、JavaScriptが定義されていないオブジェクトを渡すことを約束しました。今は論理を理解しています。 – NinetyHH

+0

ええ、あなたが定義されていないもののプロパティを読み込もうとすると、JavaScriptがうまくいきません。お役に立てて嬉しいです! – jasonmerino

関連する問題