Ant Design form set values form props

Selvin picture Selvin · Dec 10, 2018 · Viewed 15.7k times · Source

I'm using antd design in my form.

Here I'm setting value from reducer profilereducer by using shouldComponentUpdate method.

class ProfileForm extends Component {

 componentDidMount = () => {
  this.props.actions.getprofile()
 }

 shouldComponentUpdate = (nextProps) => {
  if (this.props.profile) {
   this.props.form.setFieldsValue({
    name: this.props.profile.name,
   });
  } else {
   this.props.form.setFieldsValue({
    firstname: 'loading',
   });
  }
 }


 render() {
  const { getFieldDecorator, getFieldValue } = this.props.form; 
     <Form layout="vertical">
        <FormItem label="First Name" >
            {getFieldDecorator('name', { rules: [{ required: true, message: 'Required!', }], })(
                <Input addonBefore={selectBefore} placeholder="First Name" />
            )}
        </FormItem>
    </Form>    
}


 function mapStateToProps(state) {
  return {
   profile: state.profilereducer.profile,
  }
 }

 function mapDispatchToProps(dispatch) {
  return {
   actions: bindActionCreators(actions, dispatch)
  }
 }

 const Profile = Form.create()(ProfileForm);

 export default connect(mapStateToProps, mapDispatchToProps)(Profile);
}

Error:

enter image description here

Answer

Hemanthvrm picture Hemanthvrm · Dec 10, 2018

You are setting state in a loop, hence you got the error. Here is a better approach of dealing it.. I just left selectBefore as a variable(in your code, i haven't found setting it).. Change it to string if you get error..

componentDidMount = () => {
   this.props.actions.getprofile()
  }

  renderBasicform(initialVal) {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    return (
      <Form layout="vertical">
        <FormItem label="First Name" >
          {getFieldDecorator('name', { initialValue: initialVal,rules: [{ required: true, message: 'Required!', }], })(
            <Input addonBefore={selectBefore} placeholder="First Name" />
          )}
        </FormItem>
      </Form>
    );
  }

  render() {
    if(!this.props.profile) {
        return (
          <div>
          {this.renderBasicform("Loading")}
          </div>
        );
    }

        return (
          <div>
            {this.renderBasicform(this.props.profile.name)}
            </div>
        );
  }