【发布时间】:2018-02-27 19:34:35
【问题描述】:
组件 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: Cannot read property 'catch' of undefined
组件登录页面
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)));
你能解释一下为什么 undefined catch 吗?函数使用 promise then() 提交返回结果。
【问题讨论】:
-
您正在返回
.then,这是.login函数的结果 -
显然是因为
this.props.submit没有返回任何东西 -
将
submit = data => { this.props.login(data).then(() => this.props.history.push("/")); }更改为submit = data => this.props.login(data).then(() => this.props.history.push("/"));或submit = data => { return this.props.login(data).then(() => this.props.history.push("/")); } -
@Sag1v 不,没有任何返回
-
阅读 arrow documentation 以了解拥有
{}和没有{}之间的区别 - 即"concise body"
标签: javascript reactjs promise