我正在尝试在屏幕上的Redux From Fields中加载我之前的值,并希望在用户更新值时从每个字段获取新值。我尝试了几种不同的方式,例如onChange
或initialValues
,但到目前为止,我仍然没有运气让它运转起来:
到目前为止,这是我的代码:
`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);`
目前这给了我错误:
TypeError:无法读取未定义
的属性'surveyEdit'
this.props.surveyEdit
这是我从数据库中获取的对象,我希望用它来为字段提供初始值。在我尝试的时候,我也无法在屏幕上看到以前的价值。
任何人都有更好的主意?我很确定必须有办法做到这一点,我似乎无法理解如何实现它。
一如既往地感谢您!