首页 > 解决方案 > 将 Formik JSON 反应为 YAML,然后在提交时返回 JSON

问题描述

我的目标是将一个 JSON 对象字符串化为 YAML 作为字段值,然后在提交表单时,获取 YAML 并将其转换为 JSON。

我能够获取 JSON,并使用在要使用YAML 节点包YAML.stringify(options, null, 2);进行编辑的字段中获取 YAML 值。但是,提交后我不确定如何将 YAML 解析为 JSON。

在我的组件底部附近,我试图push JSON.stringify('', null, 0)获得价值,但我一直在获得 YAML。

如何使用 Formik 将已编辑的 YAML 字段解析回 JSON 以获取数据onSubmit

是采用编辑过的 YAML 并将其转换为 JSON 以提交前端可能的内容,还是我必须添加后端逻辑?我找到了转换器,但在这种情况下并不多。

我的 JSON 数据(重点是"options"关键):

{
  "id": "1",
  "photo_name": "Testing",
  "options": {
    "test": true,
    "command": [
      "test photo"
    ],
    "max_size": 50,
    "is_prio": false
  },

YAML 输出:

test: true
command:
  - test photo
max_size: 50
is_prio: false

我的反应组件:

import YAML from 'yaml';

const NewPhoto = () => {
  const fetchContext = useContext(FetchContext);
  const [photoList, setphotoList] = useState([]);

  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

  useEffect(() => {
    const getphotoList = async () => {
      try {
        const { data } = await fetchContext.authAxios.get(`/api/photo_data/`);
        setphotoList(data.results);
      } catch (err) {
        console.log(err);
      }
    };

    getphotoList();
  }, [fetchContext]);

  const initialValues = {
    id: '',
    options: '',
  };

  return (
    <div className="col-xl-12">
      <Formik
        initialValues={initialValues}
        onSubmit={async (values, { resetForm }) => {
          alert(JSON.stringify(values, null, 2));
          resetForm();
        }}
        validationSchema={schema}
      >
        {({ isSubmitting, values, setFieldValue, handleChange }) => (
          <Form>
            <FieldArray name="photo">
              {({ insert, remove, push }) => (
                <>
                  {values.photo.length > 0 &&
                    values.photo.map((task, index) => (
                      <div className="row" key={index}>
                        <div className="col-11">
                          <div className="row">
                            <div className="col">
                              <div className="form-group">
                                <label htmlFor={`photo.${index}.step`}>
                                  PHOTO TASK
                                </label>
                                <Field
                                  className="form-control"
                                  as="select"
                                  name={`photo.${index}.id`}
                                  onChange={(event) => {
                                    handleChange(event);
                                    const selectedPhotoTask = photoList.find(
                                      (photoList) =>
                                        photoList.id === event.target.value
                                    );
                                    const selectedOptions = YAML.stringify(
                                      selectedPhotoTask.options,
                                      null,
                                      2
                                    );
                                    setFieldValue(
                                      `photo.${index}.options`,
                                      selectedOptions
                                    );
                                  }}
                                >
                                  <option value="" defaultValue disabled>
                                    ...
                                  </option>
                                  {photoList &&
                                    photoList.map((task) => (
                                      <option key={task.id} value={task.id}>
                                        {task.name}
                                      </option>
                                    ))}
                                </Field>
                              </div>
                            </div>
                          </div>
                          <div className="row">
                            <div className="col-12">
                              <div className="form-group">
                                <label htmlFor={`photo.${index}.options`}>
                                  OPTIONS
                                </label>
                                <Field
                                  id="options"
                                  component="textarea"
                                  className="form-control"
                                  name={`photo.${index}.options`}
                                  type="text"
                                  rows="4"
                                  onChange={handleChange}
                                />
                              </div>
                            </div>
                          </div>
                        </div>
                        <div className="col-1">
                          <button
                            type="button"
                            className="btn"
                            onClick={() => remove(index)}
                          >
                            DELETE
                          </button>
                        </div>
                      </div>
                    ))}
                  <button
                    type="button"
                    className="btn"
                    onClick={() =>
                      push({
                        id: '',
                        options: '',
                        // options: JSON.stringify('', null, 0),
                      })
                    }
                  >
                    ADD
                  </button>
                </>
              )}
            </FieldArray>
            <button className="btn" type="submit" disabled={isSubmitting}>
              SUBMIT
            </button>
          </Form>
        )}
      </Formik>
    </div>
  );
};

export default NewPhoto;

标签: reactjsjsonyamlformik

解决方案


我需要将它们保存values到他们自己的变量中,然后遍历它们并YAML.parse()为每个索引应用一个。

    let submitVals = values;

    for (let index = 0; index < submitVals.photo.length; index++) {
      let optionsText = YAML.parse(submitVals.photo[index].options);
      submitVals.photo[index].options = optionsText;
    }
    console.log(submitVals);
    send(submitVals);

推荐阅读