7

一旦初始 props 发生变化,表单中的值需要更新

export default withFormik({
    mapPropsToValues: (props: Props) => {
        return (
            {
                id: props.initialData.id,
                name: props.initialData.name
            }
        );
    },
    handleSubmit: (values, {  props: Props, setSubmitting }) => {
      Props.submitHandler(values);
    },
  })(NewDatasourceForm);

在这里mapPropsToValues我可以得到新的props,但是表单中的值没有得到更新。

const NewDatasourceForm = (props) => {
const {
    values,
    touched,
    errors,
    isSubmitting,
    setFieldValue,
    handleSubmit,
    handleChange,
    handleBlur
} = props;

const _handleSelect = (selectDSChoice) => {
    try {
        setFieldValue('dataSourceType',  selectDSChoice.value);
    } catch (error) {
        // tslint:disable-next-line:no-console
        console.error(error);
    }

};

return(
  <form className="needs-validation was-validated p-5" onSubmit={handleSubmit}>

        <div className="form-group">
            <label>Name</label>
            <input
                className={`form-control`}
                name="name"
                type="text" 
                value={values.name} 
                onChange={handleChange}
                onBlur={handleBlur}
            />
        </div>
    </form>
);
};

https://codesandbox.io/s/k5w5qn94z7

谢谢你的支持。

4

1 回答 1

27
withFormik({
    enableReinitialize: true,
    mapPropsToValues: (props: Props) => {

添加enableReinitialize: true,解决了问题

https://github.com/jaredpalmer/formik/issues/168

于 2018-03-28T10:14:33.763 回答