使用redux-form和immutablejs重置表单

时间:2016-05-04 03:59:59

标签: reactjs redux redux-form

我一直试图处理redux-form和immutablejs,我想我已经把大部分内容都搞砸了。但是,我知道我至少缺少一步。并非我期望传递给表单组件的所有道具都被传递给它。例如,formKeyundefined。当我去尝试使用this.props.resetForm时,我注意到了这一点。该功能存在,但它似乎没有做任何事情。表单输入仍保持更改,pristine为false。这是我的表单和根减速器:

import React, {Component} from 'react';
import {reduxForm} from 'redux-form';
export const fields = [ 'firstName', 'lastName', 'email' ]

class ContactForm extends Component {
  render() {
    const {fields: {firstName, lastName, email}} = this.props;
    const handleSubmit = function (e) { 
        e.preventDefault()
        console.log('firstName', firstName.value)
    }

    const reset = function () {
      console.log('before', this.props)
      this.props.resetForm()
      console.log('after', this.props)
    }.bind(this)

    return (
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label>First Name</label>
          <input type="text" className="form-control" placeholder="First Name" {...firstName}/>
        </div>
        <div className="form-group">
          <label>Last Name</label>
          <input type="text" className="form-control" placeholder="Last Name" {...lastName}/>
        </div>
        <div className="form-group">
          <label>Email</label>
          <input type="email" className="form-control" placeholder="Email" {...email}/>
        </div>
        <button type="submit" className="btn btn-primary">Submit</button>
        <br/><br/>
        <button type="button" className="btn btn-primary" onClick={reset}>Reset</button>
      </form>
    );
  }
}

const ContactFormContainer = reduxForm({ 
  form: 'contact',                           
  fields,
  getFormState: (state, reduxMountPoint) => state.get(reduxMountPoint).toJS()
},
function (state, ownProps) {
    const contact = state.get('contacts').get(ownProps.contactId);
    return {
        initialValues: contact.toJS()
    }
}
)(ContactForm);

export default ContactFormContainer;

import Immutable, {Map, fromJS} from 'immutable'
import {reducer as formReducer} from 'redux-form';
import {combineReducers} from 'redux-immutable';
import {createStore} from 'redux';
import contacts from './contacts/reducer'

const rootReducer = combineReducers({
    form: (state = Immutable.fromJS({}), action) => Immutable.fromJS(formReducer(state.toJS(), action)),  
    contacts
});

const initialState = Map();

export default createStore(rootReducer, initialState);

1 个答案:

答案 0 :(得分:0)

这是一个老问题,所以我想你现在已经解决了,但是如果你还有问题我会建议将redux-form库升级到v6并使用Immutable.js检出示例:

http://redux-form.com/6.0.2/examples/immutable/

此示例使用的是redux-immutablejs库,但它也应该与redux-immutable一起使用,如示例所示。