typescript withFormik : 在初始值改变时,更新 props.value

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49491110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:18:32  来源:igfitidea点击:

withFormik : On initial value change, update props.value

javascriptformsreactjstypescriptformik

提问by Abel Jojo

Once the initial props changes, the values in the forms need to be updated

一旦初始 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);

Here in mapPropsToValuesI am able to get the new props, But the values in form not get updated.

在这里,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

https://codesandbox.io/s/k5w5qn94z7

Thanks for support.

感谢您的支持。

回答by Abel Jojo

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

Add enableReinitialize: true,solved the issue

添加enableReinitialize: true,解决了问题

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

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