[英]React.js - TypeError: Cannot read property 'catch' of undefined
組件LoginForm具有以下代碼:
class LoginForm extends React.Component {
.................................................................
onSubmit = (e) => {
e.preventDefault();
const errors = this.validate(this.state.data);
this.setState({ loading: true});
this.props.submit(this.state.data).catch(console.log("errors"));
}
.....................................................................
}
LoginForm.PropTypes = {
submit: PropTypes.func.isRequired
};
export default LoginForm;
當我提交按鈕時,出現錯誤TypeError:無法讀取未定義的屬性“ catch”
組件登錄頁面
class LoginPage extends React.Component {
submit = data => {
this.props.login(data).then(() => this.props.history.push("/"));
}
render() {
return(
<div className="login-page">
<main>
<div className="login-block">
<img src="assets/img/logo.png" alt=""/>
<h1>Log into your account</h1>
<LoginForm submit={this.submit} />
</div>
<div className="login-links">
<a className="pull-left" href="user-forget-pass.html">Forget Password?</a>
<a className="pull-right" href="user-register.html">Register an account</a>
</div>
</main>
</div>
);
}
}
LoginPage.propTypes = {
history: PropTypes.shape({
push: PropTypes.func.isRequired
}).isRequired,
login: PropTypes.func.isRequired
};
export default connect(null, {login})(LoginPage);
動作/授權
import { USER_LOGGED_IN } from "../types";
import api from "../api";
export const userLoggedIn = user => ({
type: USER_LOGGED_IN,
user
});
export const login = credentials => dispatch =>
api.user.login(credentials)
.then(user => dispatch(userLoggedIn(user)));
您能否解釋為什么未定義的捕獲量? 函數使用promise then()提交返回結果。
您應該將catch
移至LoginPage
:
submit = data => {
this.props.login(data)
.then(() => this.props.history.push("/"))
.catch(console.log)
}
並在需要時將錯誤作為LoginForm
傳遞給LoginForm
。
刪除承諾中的{}。 應該是這樣
submit = data => this.props.login(data).then(() => this.props.history.push("/"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.