2016-10-27 8 views
0

私が作成したリアクションコンポーネントに以下のコンストラクタと関数があります。リアクションsetStateが動作しない

constructor() { 
    super() 
    this.state = { 
     error: false 
    } 
} 

handleSubmit(e) { 
    e.preventDefault() 
    const email = this.refs.email.value 
    const password = this.refs.password.value 
    const self = this 

    firebase.auth().signInWithEmailAndPassword(email, password).then(
     function(result) { 
      const location = self.props.location 
      if (location.state && location.state.nextPathname) { 
       self.context.router.replace(location.state.nextPathname) 
      } else { 
       self.context.router.replace("/home") 
      } 
      // User signed in! 
      console.log("User signed in!") 
    }).catch(function(error) { 
     this.setState({error: error}) // Error points to this line 
    }) 
} 

私は、コンソールで次のエラーを取得しておいてください。

Uncaught TypeError: Cannot read property 'setState' of undefined

誰もが私の問題の特定に役立つことはできますか?あなたは

catch(function(error) { 
    this.setState({error: error}) // Error points to this line 
}) 

を「自己」を使用する必要があり、次のコードでは

+0

する必要がありますが値を取得するには、 'refs'を使用する必要があります?コンポーネントが 'input'要素の場合は、' onChange'イベントを使用して変数を値で更新することができます。 –

+0

'refs 'を使ってそれを使う利点はありますか? –

+0

Refsは、ドキュメントに従ってイベント、州または小道具で同じことをすることができない場合、最後の手段であるべきです。また、浅いレンダリングはユニットテスト時には機能しません。 –

答えて

2

、あなたは「この」を使用は、

catch(function(error) { 
    self.setState({error: error}) // Error points to this line 
}) 
+1

矢印関数を使用することもできます。 'this'は' handleSubmit'のレキシカルスコープを継承します。 – ken4z

+0

ありがとう、働いた!私もユーザーに 'error:error.message'を持っていなければなりませんでしたが、それは私の質問の範囲外です –

+0

@ ken4zどうすればいいですか? –

関連する問題