2016-10-27 7 views
0

나는 내가 만든 반응 구성 요소에 다음과 같은 생성자와 함수를 가지고있다.React setState not working

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

사람이 내 문제를 식별 할 수 있습니까? 당신이 '자기'를 사용해야 할 때 다음 코드에서

+0

당신이 값을 얻기 위해'refs'를 사용해야 할 수 있어야 ? 컴포넌트가'input' 요소라면'onChange' 이벤트를 사용하고 변수를 값으로 업데이트 할 수 있습니다. –

+0

'refs '를 사용하면 이점이 있습니까? –

+0

Refs는 문서에 따라 이벤트, 주 또는 소품으로 동일하게 수행 할 수없는 최후의 수단이어야합니다. 또한 유닛 렌더링시 얕은 렌더링이 작동하지 않습니다. –

답변

2

, 사용 '이',

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

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

화살표 함수를 사용할 수도 있고'this'는'handleSubmit'의 어휘 범위를 상속받을 것이다 – ken4z

+0

고마워, 저것 일했다! 나는 또한 사용자에게'error : error.message'를해야만했다. 내 질문의 범위를 벗어났다. –

+0

@ ken4z 어떻게하면 좋을까? –