为什么我不能在生命周期方法中设置React组件状态

时间:2016-09-11 01:34:28

标签: reactjs web-applications firebase-authentication

我正在使用以下Container代码显示SnackBar,如果用户的电子邮件已存在另一个帐户,如果我删除这行代码(this.setState({ open: true }))小吃栏通过使用按钮设置状态显示正常:

class HomeContainer extends Component {

  static propTypes = {
    authError: PropTypes.string,
    removeError: PropTypes.func.isRequired
  }

  static contextTypes = {
    router: PropTypes.object.isRequired
  }

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

// ////////////////////////////////////////////////////////////////////////////////////////////////
// the following componetdid mount function is only required when using SigninwithRedirect Method - remove when using SigninWithPopup Method
  componentDidMount () {
    firebaseAuth.getRedirectResult().then((authUser) => {
    // The signed-in user info.
      console.log('User Data from Oauth Redirect: ', authUser)
      const userData = authUser.user.providerData[0]
      const userInfo = formatUserInfo(userData.displayName, userData.photoURL, userData.email, authUser.user.uid)
      return (this.props.fetchingUserSuccess(authUser.user.uid, userInfo))
    })
    .then((user) => {
      return saveUser((user.user))
    })
    .then((user) => {
      return (this.props.authUser(user.uid))
    }).then((user) => {
      this.context.router.replace('feed')
    }).catch(function (error) {
      // Handle Errors here.
      const errorCode = error.code
      const errorMessage = error.message
      // The email of the user's account used.
      const email = error.email
      // The firebase.auth.AuthCredential type that was used.
      const credential = error.credential
      // if error is that there is already an account with that email
      if (error.code === 'auth/account-exists-with-different-credential') {
        // console.log(errorMessage)
        firebaseAuth.fetchProvidersForEmail(email).then(function (providers) {
           // If the user has several providers,
          // the first provider in the list will be the "recommended" provider to use.
          console.log('A account already exists with this email, Use this to sign in: ', providers[0])
          if (providers[0] === 'google.com') {
            this.setState({ open: true })
          }
        })
      }
    })
  }

  handleRequestClose = () => {
    this.setState({
      open: false
    })
  }

// /////////////////////////////////////////////////////////////////////////////////////////////////////

  render () {
    return (
      <div>
      <Snackbar
          open={this.state.open}
          message= 'A account already exists with this email'
          autoHideDuration={4000}
          onRequestClose={this.handleRequestClose.bind(this)}/>
      <Home />
      </div>
    )
  }
}

1 个答案:

答案 0 :(得分:0)

我在功能(提供商)&amp ;;功能(错误)。将它们切换到箭头功能,并且定义了它的外部范围。 :)