Uncatch TypeError:_this.props.onSubmit 在使用 redux-form 时不是一个函



我正在使用 React.js 前端,当我尝试登录或注册时,单击loginSign up按钮时出现以下错误。

Uncaught TypeError: _this.props.onSubmit is not a function

堆栈跟踪指向以下文件,

/

src/containers/Login/index.js

// @flow
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { Link } from 'react-router-dom';
import { css, StyleSheet } from 'aphrodite';
import Input from '../../components/Input';
const styles = StyleSheet.create({
  card: {
    maxWidth: '500px',
    padding: '3rem 4rem',
    margin: '2rem auto',
  },
});
type Props = {
  onSubmit: () => void,
  handleSubmit: () => void,
  submitting: boolean,
}
class LoginForm extends Component {
  props: Props
  handleSubmit = (data) => this.props.onSubmit(data);
  // handleSubmit: (data) => this.props.onSubmit(data);

  render() {
    const { handleSubmit, submitting } = this.props;
    return (
      <form
        className={`card ${css(styles.card)}`}
        onSubmit={handleSubmit(this.handleSubmit)}
      >
        <h3 style={{ marginBottom: '2rem', textAlign: 'center' }}>Login to Sling</h3>
        <Field name="email" type="text" component={Input} placeholder="Email" />
        <Field name="password" type="password" component={Input} placeholder="Password" />
        <button
          type="submit"
          disabled={submitting}
          className="btn btn-block btn-primary"
        >
          {submitting ? 'Logging in...' : 'Login'}
        </button>
        <hr style={{ margin: '2rem 0' }} />
        <Link to="/signup" className="btn btn-block btn-secondary">
          Create a new account
        </Link>
      </form>
    );
  }
}
const validate = (values) => {
  const errors = {};
  if (!values.email) {
    errors.email = 'Required';
  }
  if (!values.password) {
    errors.password = 'Required';
  }
  return errors;
};
export default reduxForm({
  form: 'login',
  validate,
})(LoginForm);

具体来说,是以下一行,

  handleSubmit = (data) => this.props.onSubmit(data);

再次,非常感谢任何和所有的帮助。

最后,可以在这里找到整个项目。

handleSubmit是通过 redux-form "注入"到组件中的道具,onSubmit不是......您要么必须确保自己提供它,要么只是处理表单提交LoginForm#handleSubmit

您也可以这样做:https://github.com/erikras/redux-form/issues/1163

引用:

  • http://redux-form.com/6.0.0-alpha.4/docs/faq/HandleVsOn.md/

在你的App/index.js中,你做了

 <RedirectAuthenticated path="/login" component={Login} {...authProps} /> 

您可以看到您没有将onSubmit函数传递给登录组件

您可以通过对App/index.js进行这些更改来修复它

// add this function
const LoginComponent = () => {
    return (
        <Login onSubmit={() => { console.log("hi") }} />
    )   
}
class App extends Component {
    ...
   render() {
     ....
     <RedirectAuthenticated path="/login" component={LoginComponent} {...authProps} />

在这种情况下,您将看到"hi"打印到开发控制台。

最新更新