0

在我的 LoginForm 组件中调用 onSubmit 时,我的回调函数“login”被正确调用,但代码的 async/await 部分被跳过。Console.log 1 和 2 被调用,我在控制台中看到它们,但 console.log 3,它位于代码的 async/await 部分内,从未运行。它被跳过,然后 console.log 4 被调用。任何帮助将不胜感激。

import React from 'react';
import { Form, Segment, Button, Label } from 'semantic-ui-react';
import { connect } from 'react-redux'
import { withFirebase } from 'react-redux-firebase'
import { Field, reduxForm, SubmissionError } from 'redux-form';
// import { login } from '../authActions'


class LoginForm extends React.Component {

render(){
   const { handleSubmit, error, firebase} = this.props
   console.log('4: LoginForm->render->firebase:',firebase)

   const myLogin = (credentials) => {
       console.log('1: myLogin fired',credentials)
       const {firebase} = this.props;
       console.log('2: myLogin -> firebase',firebase)

       return async (firebase)=> {
         console.log('3: async -> myLogin -> firebase: ', firebase)
        try {
          await firebase.auth().signInWithEmailAndPassword(credentials.email, 
credentials.password);
          console.log('try fired')
        } catch (error) {
          console.log(error);
          throw new SubmissionError({
        _error: 'Login failed'
          })
        }
      }

}
    return (
    <Form size="large" onSubmit={handleSubmit(myLogin)}>
  <Segment>
    <Field
      name="email"
      component={Form.Input}
      type="text"
      placeholder="Email Address"
    />
    <Field
      name="password"
      component={Form.Input}
      type="password"
      placeholder="password"
      />
             {error && <Label basic color='red'>{error}</Label>}
            <Button fluid size="large" color="teal">
          Login
        </Button>

      </Segment>
    </Form>
  );
};
};

const mapState = (state) => ({
firebase: state.firebase
})

//Attempted to use an action creator to log use in, but couldn't get it to work so I moved the auth call inside the component and called it myLogin
// const actions = {
//   login
// }

export default withFirebase(
connect(mapState, null)(reduxForm({form: 'loginForm'})(LoginForm))
  )
4

1 回答 1

0

myLogin是一个带有参数的函数,credentials它返回另一个async带有firebaseawait承诺的参数的函数firebase.auth()...

handleSubmit将调用您的myLogin函数并将表单数据传递给它。 看这里

所以在你的myLogin函数中你需要做你想做的一切,而不是返回一个永远不会被调用的函数。尝试类似:

const myLogin = (credentials) => {
    console.log('1: myLogin fired',credentials)
    const {firebase} = this.props;
    console.log('2: myLogin -> firebase',firebase)

    try {
        console.log('3: async -> myLogin -> firebase: ', firebase)
        await firebase.auth().signInWithEmailAndPassword(credentials.email, 
            credentials.password);
        console.log('try fired')
    } catch (error) {
        console.log(error);
        throw new SubmissionError({
            _error: 'Login failed'
        })
    }
}

于 2019-01-30T22:30:26.063 回答