【发布时间】:2019-04-04 03:57:44
【问题描述】:
嘿,伙计们,我一直试图弄清楚我现在遇到的这个问题,但无济于事。我有一个表单,它通过 firebase 验证电子邮件和密码以让一个人登录,当此验证失败时,我想向我的表单抛出一个错误,然后将显示内联以让用户知道登录失败。我的问题是每当我遇到错误时,我都会抛出错误:
我的代码如下:
LoginForm.jsx
import React, { Component } from "react";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import { reduxForm, Field } from "redux-form";
import { Form, Button, Grid, Label } from "semantic-ui-react";
import { login } from "../authActions";
import TextInput from "../../../app/common/form/TextInput";
const actions = {
login
};
class LoginForm extends Component {
initiateLogin = values => {
this.props.login(values, this.props.history);
};
onFormSubmit = values => {
this.initiateLogin(values);
};
render() {
const { error } = this.props;
return (
<Grid>
<Grid.Column width={16}>
<Form
size="large"
onSubmit={this.props.handleSubmit(this.onFormSubmit)}
>
<Field
name="email"
type="text"
component={TextInput}
placeholder="email"
/>
<Field
name="password"
type="text"
component={TextInput}
placeholder="Password"
/>
{error && (
<Label basic color="red">
{error}
</Label>
)}
<Button className="loginBtn">Login</Button>
</Form>
</Grid.Column>
</Grid>
);
}
}
export default withRouter(
connect(
null,
actions
)(reduxForm({ form: "loginForm" })(LoginForm))
);
authActions.jsx
import { SubmissionError } from "redux-form";
import { SIGN_OUT_USER } from "./authConstants";
import { closeModal } from "../modals/modalActions";
export const login = (creds, history) => {
return async (dispatch, getState, { getFirebase }) => {
const firebase = getFirebase();
try {
console.log("zero");
await firebase
.auth()
.signInWithEmailAndPassword(creds.email, creds.password);
console.log("first");
dispatch(closeModal());
console.log("second");
history.push("/profile");
console.log("third");
} catch (error) {
throw new SubmissionError({
_error: "Login Failed"
});
}
};
};
export const logout = () => {
return {
type: SIGN_OUT_USER
};
};
因此,在提交表单时,我调用 handleSubmit 并传递我自己的自定义方法,然后该方法继续调用我的 authAction 方法之一。如果登录不起作用,则此方法会引发 SubmissionError ,理论上我希望在我的错误道具中的 LoginForm 中更新此错误,以便我可以使用内联错误消息更新 dom。
问题是我无法从我的登录 authAction 中执行“抛出新的 SubmissionError”。我认为这与未返回的承诺(和/或)我如何使用我的 handleSubmit 方法有关。我环顾四周,但无法得到任何工作。
谢谢各位。
【问题讨论】:
-
this.initiateLogin(values).catch(err => do something with the error here perhaps) -
我收到错误:TypeError: Cannot read property 'catch' of undefined
-
哦,是的,...因为你需要
return this.props.login(values, this.props.history); -
啊好的,所以我会在我的第一个方法中添加 catch 并从我的initialLogin 方法返回承诺,这很有意义。我一天无法尝试,但我会在星期四回复您
-
Sweet 所以我可以在 catch 中返回错误,但是我现在如何像我想要的那样更新我的 dom?那么现在标签显示错误?另外我仍然得到前两个错误
标签: reactjs promise form-submit redux-form