хотите загрузить начальные значения в форме Redux

я пытаюсь загрузить начальное значение из, но не могу этого сделать, я использую redux-from , я установил данные профиля в хранилище избыточности и могу получить доступ к данным через реквизит (консольировать их), но не могу отобразить в форме ввода. я пытаюсь воспроизвести этот пример из redux-from., но не смог продолжить его.

ниже приведен код.

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

import { required, email, maxLength25 } from '../utils/validations';
import { renderField,
    renderSelectField,
    renderRadioField,
    renderTextAreaField,
    renderCheckboxField
} from '../utils/textFieldGroup';
import countries from '../utils/countryList';
import { profileUpdate, profile } from '../actions/user';

const validateAndUpdateRecords = (values, dispatch) => {
    return dispatch(profileUpdate(values))
    .then((response) => {
        console.log(response);
    })
    .catch((error) => {
        console.log(error);
    })
}

class ProfileForm extends React.Component {
    componentWillMount(dispatch){
        console.log('mount');
        this.props.fetchProfile();
    }

    render(){
        const { handleSubmit, submitSucceeded, error, profile } = this.props
        console.log('prof',profile);

        return (
            <div>
                <h1>Profile Page</h1>
                <form onSubmit={handleSubmit(validateAndUpdateRecords)}>
                    <div className={typeof error!='undefined'?'show alert alert-danger': 'hidden'}>
                     <strong>Error!</strong> {error}
                    </div>
                    <Field name="fname" type="text" component={renderField} label="First Name"
                      validate={[ required, maxLength25 ]}
                    />
                    <Field name="lname" type="text" component={renderField} label="Last Name"
                      validate={[ required, maxLength25 ]}
                    />
                    <Field component={renderRadioField} name="gender" label="Gender" options={[
                        { title: 'Male', value: 'male' },
                        { title: 'Female', value: 'female' }
                    ]} validate={ required } />
                    <Field name="country" type="text" data={countries} component={renderSelectField} label="Country"
                      validate={[ required ]}
                    />
                    <Field name="about_us" type="text" component={renderTextAreaField} label="About Us"
                      validate={[ required ]}
                    />
                    <Field name="newsletter" type="checkbox" component={renderCheckboxField} label="Newsletter"
                      validate={[ required ]}
                    />
                    <p>
                      <button type="submit" disabled={submitSucceeded} className="btn btn-primary btn-lg">Submit</button>
                    </p>
                </form>
            </div>
        )
    }
}

ProfileForm = reduxForm({
    form:'profile'
})(ProfileForm)

ProfileForm = connect(
  state => ({
    initialValues: state.user.profile 
  })              
)(ProfileForm)

export default ProfileForm;

//текстовое поле

export const renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
    <div className={classnames('form-group', { 'has-error':touched && error })}>
      <label className="control-label">{label}</label>
      <div>
        <input {...input} placeholder={label} type={type} className="form-control"/>
        {touched && ((error && <span className="help-block">{error}</span>))}
      </div>
    </div>
)

заранее спасибо


person Rahul Mangal    schedule 29.01.2017    source источник
comment
все вхождения .props в вашем фрагменте кода? у вас должно быть любое <obj>.props, где <obj> не определено. В ваших фрагментах кода единственные вхождения ar в render() и componentWillMount() определены ли там this?   -  person NonPolynomial    schedule 29.01.2017
comment
привет @NonPolynomial, извините, я не мог понять, что вы сказали, не могли бы вы объяснить подробнее, я также использую компонент формы этого профиля в этом контейнере (codepen.io/mglrahul/pen/ZLaZvM?editors=0010), с нетерпением жду вашего ответа, спасибо.   -  person Rahul Mangal    schedule 29.01.2017
comment
@NonPolynomial, я нахожу решения, спасибо   -  person Rahul Mangal    schedule 29.01.2017


Ответы (1)


Наконец я выясняю решения. ниже решения. Нам нужно добавить enableReinitialize : true, как указано ниже. Если наш реквизит initialValues ​​обновится, форма тоже обновится.

ProfileForm = reduxForm({
    form:'profile',
    enableReinitialize : true
})(ProfileForm)
person Rahul Mangal    schedule 29.01.2017