Input onchange checker if data exist in JSON data

白昼怎懂夜的黑 提交于 2019-12-24 11:18:58

问题


I have a user requirement when adding a form it should check if the name of the form is already exist. How can I do that in es6? I'm using AntDesign and ReactJS.

Here's my code

<Form.Item label="Form Name">
  {getFieldDecorator('formName', {
   rules: [formConfig],
  })(<Input name="formName" onChange={onChange} />)}
</Form.Item>
const handleChange = e => {
  const { name, value } = e.target;

   setState(() => ({
     ...state,
     [name]: value,
   }));

   let isExist = [...formDataSource];
    let foundExistItem = isExist.filter(
      item => item.formName === formName
    );
 };

回答1:


If you want dynamically query the form fields, you should wrap your form with Form.create.

It injects useful functionalities like onFieldsChange listener:

const onFieldsChange = (_, changedFiels) => {
  const { username } = changedFiels;
  if (username) {
    // Make your API checks
    console.log(`Now changing ${username.name}`);
  }
};

const ValidatedFields = Form.create({ onFieldsChange })(App);

Note: You should keep your Form.Items uncontrolled using getFieldDecorator therefore avoiding onChange while collecting form data.

If you still insist to make form items controlled, you should use getFieldValue:

const handleChange = e => {
  const { name, value } = e.target;
  const { getFieldValue } = form;

  setState(() => ({
    ...state,
    [name]: value
  }));

  // or use getFieldValue for a single query
  const values = getFieldsValue(['formName',...more fields]);

  if (values.length) {
    // API CALL
  }
};



来源:https://stackoverflow.com/questions/58289639/input-onchange-checker-if-data-exist-in-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!