问题
I am trying to load my previous values in Redux From Fields on screen and hoping to get new values from each fields as a user updates the values. I have tried couple different ways, like onChange
or initialValues
but so far I still have no luck to get it working:
Here is my code so far:
`import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { reduxForm, Field } from 'redux-form';
import { Link } from 'react-router-dom';
import SurveyField from './SurveyField';
import { fetchOneSurvey } from '../../actions';
import validateEmails from '../../utils/validateEmails';
import formFields from './formFields';
class SurveyEditForm extends Component {
componentDidMount() {
const id = window.location.pathname.split('/')[2];
this.props.fetchOneSurvey(id);
}
renderFields() {
return _.map(formFields, ({ label, name }) => {
return (
<Field
key={name}
component={SurveyField}
type="text"
label={label}
name={name}
/>
);
});
}
render() {
return (
<div>
{/*.handleSubmit is from reduxForm method*/}
<form
onSubmit={this.props.handleSubmit(
this.props.onSurveySubmit
)}
>
{this.renderFields()}
<Link to="/surveys" className="red btn-flat white-text">
Cancel
</Link>
<button
type="submit"
className="teal btn-flat right white-text"
>
Next
<i className="material-icons right">done</i>
</button>
</form>
</div>
);
}
}
function validate(values) {
const errors = {};
errors.recipients = validateEmails(values.recipients || '');
_.each(formFields, ({ name }) => {
if (!values[name]) {
errors[name] = 'You must provide a value';
}
});
return errors;
}
function mapStateToProps(state) {
return {
surveyEdit: state.surveyEdit
};
}
SurveyEditForm = connect(mapStateToProps, { fetchOneSurvey })(SurveyEditForm);
SurveyEditForm = connect(state => ({
initialValues: {
title: this.props.surveyEdit.title
}
}))(SurveyEditForm);
export default reduxForm({
validate,
form: 'surveyEditForm',
destroyOnUnmount: false,
enableReinitialize: true
})(SurveyEditForm);`
This currently gives me error:
TypeError: Cannot read property 'surveyEdit' of undefined
this.props.surveyEdit
this is the object I fetched from the database and I was hoping to use it to provide initial values to the field. I also couldn't see previous value on screen while I was trying.
Anyone have better idea? I am pretty sure there must be a way to do it, I just can't seem to comprehend how to implement it.
Thank you in advance as always!
来源:https://stackoverflow.com/questions/49663215/how-to-load-previous-values-in-redux-from-field-on-screen-and-get-the-new-values