首页 文章

reduxForm - 更新后的initialValues不适用

提问于
浏览
5

我使用Redux表单版本6.8.0 .

我有一个表单组件,它通过“mapStateToProps”函数得到它的“initialValues” . 在第一次渲染时,一切都很好 .

在我的表单配置之后:

const CategoryChangeForm = reduxForm({
  form: 'change-category',
  validate: newCategoryValidate,
  enableReinitialize: true
})(CategoryChange);

当我更改字段“类别”并且更新成功时,我从firebase接收新的更新值 . 我通过提到的“mapStateToProps”函数将此更新值传递给“initialValues”:

function mapStateToProps(state, ownProps) {
    return {
    initialValues: { category: state.categories[ownProps.id].name, id: ownProps.id }
  };
}

expected 新值将应用于"category" -Field组件 . 但它没有获得更新的 Value .

我的“Field”组件的配置:

const fieldProps = {
  category: {
    name: 'category',
    type: 'text',
    placeholder: 'Bezeichnung',
    component: InputField
  },
  hidden: {
    name: 'id',
    type: 'hidden',
    component: 'input'
  }
};

这是我的表单组件:

export const CategoryChange = props => {
  const {
    color,
    message,
    handleSubmit,
    stateComponent
  } = props;

  console.log("Props: ", props);

  return (
    <span>
      <Subline color={ color } marginTop={ 70 } marginBottom={ 30 } align="center">{ message }</Subline>
      <form>
        <Field { ...fieldProps.category } />
        <Field { ...fieldProps.hidden } />
        <Button onClick={ handleSubmit(changeCategory.bind(stateComponent)) }>Ändern</Button>
        <Button marginBottom={ 5 } marginTop={ 10 }>Löschen</Button>
      </form>
    </span>
  );
}

我可以观察到更新后,我的表单组件重新呈现2次 . 第一次将其“初始化”的道具设置为“真实” . 但它第二次设置为“假” . 第二次渲染是由于包装我的表单组件的hoc组件的stateChange而发生的 . 更新成功时会触发the hoc的“setState”,并向用户显示相应的消息 . 但是第二次渲染的原因是表单组件没有初始化 .

如果您还需要更多代码,请与我们联系 .

希望有人提示解决这个问题......

1 回答

  • 3

    According to the docs

    默认情况下,您只能通过initialValues初始化一次表单组件 . 有两种方法可以使用新的“pristine”值重新初始化表单组件:将enableReinitialize prop或reduxForm()配置参数设置为true,以允许每次initialValues prop更改时使用新的“pristine”值重新初始化表单 . 要在重新初始化时保留脏表单值,可以将keepDirtyOnReinitialize设置为true . 默认情况下,重新初始化表单会使用“pristine”值替换所有脏值 . 发送INITIALIZE操作(使用redux-form提供的操作创建器) .

    您可以将 CategoryChangeForm 从函数更改为类,并在 componentWillReceiveProps 方法中从 redux-forms 调用 initialize 操作 .

    import {initialize} from 'redux-form'
    
    CategoryChangeForm extends Component {
         ...
         componentWillReceiveProps(nextProps) {
           // check the props and call initialize when needed
         } 
    }
    
    mapDispatchToProps = dispatch =>  ({
        initialize: (data) => initialize('change-category', data)
    })
    

相关问题