2017-01-29 8 views
0

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

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

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> 
) 

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

+1

все происшествия '.props' в вашем фрагменте кода? вы должны иметь любые ' .props', где' 'ist undefined. В ваших фрагментах кода единственные события ar в 'render()' и 'componentWillMount()', '' 'это' там определено? – NonPolynomial

+0

hi @NonPolynomial, извините, я не мог понять, что вы сказали, не могли бы вы объяснить больше, я также использую этот компонент формы профиля в этом контейнере (http://codepen.io/mglrahul/pen/ZLaZvM?editors=0010), с нетерпением жду вашего ответа, спасибо. –

+0

@NonPolynomial, я выясняю решения, спасибо –

ответ

2

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

ProfileForm = reduxForm({ 
    form:'profile', 
    enableReinitialize : true 
})(ProfileForm)