最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - redux-form onSubmit refreshes page - Stack Overflow

programmeradmin4浏览0评论

I am new to redux-form and I'm having a strange issue with handling onSubmit.

When I set up my project exactly as in the redux-form example here .7.0/examples/syncValidation/ it works as expected. I have attempted to extend this example for my needs and have confirmed that it works as expected when it loads the form like so: route ponent > form.

The issue arises when I attempt to load the form within a react ponent which is loaded via a route (route ponent > container ponent > form). When I click submit the field values are added to the address bar and form validation doesn't run. I have tried absolutely everything I can think of to fix this. The code provided below will work correctly if you replace <Main /> with <RegisterForm handleSubmit={showResults} /> in index.js. Any ideas where I'm going wrong here?

RegisterForm.js:

import React from 'react';
import { Field, reduxForm } from 'redux-form';

const validate = values => {
    const errors = {};

    if (!values.name) {
        errors.name = 'Required';
    } else if (values.name.length <= 2) {
        errors.username = 'Must be 2 characters or more';
    } else if (values.name.length > 50) {
        errors.username = 'Must be 50 characters or less';
    }

    if (!values.email) {
        errors.email = 'Required';
    } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]    {2,4}$/i.test(values.email)) {
        errors.email = 'Invalid email address';
    }

    if (!values.password) {
        errors.password = 'Required';
    } else if (!values.confirm) {
        errors.confirm = 'Required';
    } else if (values.password !== values.confirm) {
        errors.confirm = 'Passwords do not match';
    }
    return errors;
};
const renderField = ({ input, label, type, id, meta: { touched, error, warning } }) => (
    <div>
        <label htmlFor={id}>{label}</label>
        <div>
            <input {...input} id={id} placeholder={label} type={type} />
            {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
        </div>
    </div>
);

const RegisterForm = (props) => {
    const { handleSubmit, pristine, reset, submitting } = props
    return (
        <form onSubmit={handleSubmit}>
            <div className="row">
                <div className="medium-6 columns medium-centered">
                    <Field type="text" id="name" name="name" ponent={renderField} placeholder="name" label="Name" />
                </div>
                <div className="medium-6 columns medium-centered">
                    <Field type="text" id="email" name="email" ponent={renderField} placeholder="email" label="Email" />
                </div>
                <div className="medium-6 columns medium-centered">
                    <Field type="password" id="password" name="password" ponent={renderField} placeholder="password" label="Password" />
                </div>
                <div className="medium-6 columns medium-centered">
                    <Field type="password" id="confirm" name="confirm" ponent={renderField} placeholder="confirm" label="Confirm password" />
                </div>
                <div className="medium-6 columns medium-centered">
                    <button type="submit" disabled={submitting}>Submit</button>
                </div>
            </div>
        </form>
    );
};

export default reduxForm({
  form: 'register',  // a unique identifier for this form
  validate, 
})(RegisterForm);

Index.js(works):

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { HashRouter as Router, hashHistory } from 'react-router-dom';
const store = require('./store').configure();
import RegisterForm from './RegisterForm.jsx';
import Main from './Main.jsx';

const rootEl = document.getElementById('app'); 

const showResults = (values) => {
  window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`);
}

ReactDOM.render(
  <Provider store={store}>
    <Router history={hashHistory}>
      <div style={{ padding: 15 }}>
        <h2>Synchronous Validation</h2>
        <RegisterForm handleSubmit={showResults} />
      </div>
    </Router>
  </Provider>,
  rootEl,
);

Index.js(doesn't work):

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { HashRouter as Router, hashHistory } from 'react-router-dom';
const store = require('./store').configure();
import RegisterForm from './RegisterForm.jsx';
import Main from './Main.jsx';

const rootEl = document.getElementById('app'); 

const showResults = (values) => {
  window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`);
}

ReactDOM.render(
  <Provider store={store}>
    <Router history={hashHistory}>
      <div style={{ padding: 15 }}>
        <h2>Synchronous Validation</h2>
        <Main />
      </div>
    </Router>
  </Provider>,
  rootEl,
);

Main.js:

import React, { Component } from 'react';
import RegisterForm from './RegisterForm.jsx';

const showResults = (values) => {
  window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`);
};

class Register extends Component {
    render() {
        return (
            <RegisterForm handleSubmit={showResults} />
        );
    }
}

export default Register;

I am new to redux-form and I'm having a strange issue with handling onSubmit.

When I set up my project exactly as in the redux-form example here http://redux-form./6.7.0/examples/syncValidation/ it works as expected. I have attempted to extend this example for my needs and have confirmed that it works as expected when it loads the form like so: route ponent > form.

The issue arises when I attempt to load the form within a react ponent which is loaded via a route (route ponent > container ponent > form). When I click submit the field values are added to the address bar and form validation doesn't run. I have tried absolutely everything I can think of to fix this. The code provided below will work correctly if you replace <Main /> with <RegisterForm handleSubmit={showResults} /> in index.js. Any ideas where I'm going wrong here?

RegisterForm.js:

import React from 'react';
import { Field, reduxForm } from 'redux-form';

const validate = values => {
    const errors = {};

    if (!values.name) {
        errors.name = 'Required';
    } else if (values.name.length <= 2) {
        errors.username = 'Must be 2 characters or more';
    } else if (values.name.length > 50) {
        errors.username = 'Must be 50 characters or less';
    }

    if (!values.email) {
        errors.email = 'Required';
    } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]    {2,4}$/i.test(values.email)) {
        errors.email = 'Invalid email address';
    }

    if (!values.password) {
        errors.password = 'Required';
    } else if (!values.confirm) {
        errors.confirm = 'Required';
    } else if (values.password !== values.confirm) {
        errors.confirm = 'Passwords do not match';
    }
    return errors;
};
const renderField = ({ input, label, type, id, meta: { touched, error, warning } }) => (
    <div>
        <label htmlFor={id}>{label}</label>
        <div>
            <input {...input} id={id} placeholder={label} type={type} />
            {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
        </div>
    </div>
);

const RegisterForm = (props) => {
    const { handleSubmit, pristine, reset, submitting } = props
    return (
        <form onSubmit={handleSubmit}>
            <div className="row">
                <div className="medium-6 columns medium-centered">
                    <Field type="text" id="name" name="name" ponent={renderField} placeholder="name" label="Name" />
                </div>
                <div className="medium-6 columns medium-centered">
                    <Field type="text" id="email" name="email" ponent={renderField} placeholder="email" label="Email" />
                </div>
                <div className="medium-6 columns medium-centered">
                    <Field type="password" id="password" name="password" ponent={renderField} placeholder="password" label="Password" />
                </div>
                <div className="medium-6 columns medium-centered">
                    <Field type="password" id="confirm" name="confirm" ponent={renderField} placeholder="confirm" label="Confirm password" />
                </div>
                <div className="medium-6 columns medium-centered">
                    <button type="submit" disabled={submitting}>Submit</button>
                </div>
            </div>
        </form>
    );
};

export default reduxForm({
  form: 'register',  // a unique identifier for this form
  validate, 
})(RegisterForm);

Index.js(works):

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { HashRouter as Router, hashHistory } from 'react-router-dom';
const store = require('./store').configure();
import RegisterForm from './RegisterForm.jsx';
import Main from './Main.jsx';

const rootEl = document.getElementById('app'); 

const showResults = (values) => {
  window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`);
}

ReactDOM.render(
  <Provider store={store}>
    <Router history={hashHistory}>
      <div style={{ padding: 15 }}>
        <h2>Synchronous Validation</h2>
        <RegisterForm handleSubmit={showResults} />
      </div>
    </Router>
  </Provider>,
  rootEl,
);

Index.js(doesn't work):

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { HashRouter as Router, hashHistory } from 'react-router-dom';
const store = require('./store').configure();
import RegisterForm from './RegisterForm.jsx';
import Main from './Main.jsx';

const rootEl = document.getElementById('app'); 

const showResults = (values) => {
  window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`);
}

ReactDOM.render(
  <Provider store={store}>
    <Router history={hashHistory}>
      <div style={{ padding: 15 }}>
        <h2>Synchronous Validation</h2>
        <Main />
      </div>
    </Router>
  </Provider>,
  rootEl,
);

Main.js:

import React, { Component } from 'react';
import RegisterForm from './RegisterForm.jsx';

const showResults = (values) => {
  window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`);
};

class Register extends Component {
    render() {
        return (
            <RegisterForm handleSubmit={showResults} />
        );
    }
}

export default Register;
Share Improve this question asked May 24, 2017 at 5:29 adam_thadam_th 4074 silver badges11 bronze badges 1
  • 1 <Form onSubmit={this.props.handleSubmit(mySubmitHandler)}> worked for me. – totymedli Commented Oct 19, 2018 at 11:58
Add a ment  | 

1 Answer 1

Reset to default 8

You should pass in your submit handler to the onSubmit prop, not handleSubmit. It es in to your form ponent as handleSubmit, so that code should be fine.

class Register extends Component {
    render() {
        return (
            //change this
            <RegisterForm onSubmit={showResults} />
        );
    }
}
发布评论

评论列表(0)

  1. 暂无评论