Как управлять вложенными сложными объектами с помощью Formik - PullRequest
0 голосов
/ 28 сентября 2019

Я использовал библиотеку Formik для работы с вложенным объектом.Итак, я попытался FormArray внутри FormArray, но это не правильно рендеринга.Как я могу это исправить?

Пробовал разные способы обработки вложенного объекта, который у меня был, но проблема была в том, что Field не рендерится, как я хотел.

import React from "react";
import { Formik, Form, Field, FieldArray } from "formik";

// Here is an example of a form with an editable list.
// Next to each input are buttons for insert and remove.
// If the list is empty, there is a button to add an item.
const FriendList = () => (
  <div>
    <h1>Friend List</h1>
    <Formik
      initialValues={{ 
        subSkillName: "",
        queries: [
            {
                query: "",
                intent: '',
                entities: [{

                    entityName: "",
                    entityValue: '',


                }]

            }
        ] }}
      onSubmit={values =>
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
        }, 500)
      }
      render={({ values }) => (
        <Form>
            <Field name='subSkilName' placeholder='subskillname'></Field>
          <FieldArray
            name="queries"
            render={arrayHelpers => (
              <div>
                {values.queries && values.queries.length > 0 ? (
                  values.queries.map((friend, index) => (
                    <div key={index}>
                        <label>subskillname</label>
                      <Field name={`queries.${index}.query`} placeholder='query'/>
                      <Field name={`queries.${index}.intent`} placeholder='intent'/>

                      <FieldArray name={`queries.${index}.entities`}
                      render={arrayHelpers => (
                          <div>
                               {(values.queries[index]).entities && (values.queries[index]).entities.length > 0 ? (
                                  (values.queries[index]).entities.map((entity, entityindex) => {
                                    <div key={entityindex}>
                                        {console.log('came to the entity')}

                                       <Field name={`queries.${index}.entities.${entityindex}.entityName`} ></Field>

                                   </div>
                                  })

                               ):(<button type="button" onClick={() => arrayHelpers.push({

                                entityName: "",
                                entityValue: '',


                            }
                        )}>
                        {/* show this when user has removed all friends from the list */}
                        Add a queries
                      </button>) }
                          </div>


                      )}
                      >


                      </FieldArray>

                      <button
                        type="button"
                        onClick={() => arrayHelpers.remove(index)} // remove a friend from the list
                      >
                        -
                      </button>
                      <button
                        type="button"
                        onClick={() => arrayHelpers.push({


                                    query: "",
                                    intent: '',
                                    entities: []

                                }
                            )} // insert an empty string at a position
                      >
                        +
                      </button>
                    </div>
                  ))
                ) : (
                  <button type="button" onClick={() => arrayHelpers.push({

                            query: "",
                            intent: '',
                            entities: []

                        }
                    )}>
                    {/* show this when user has removed all friends from the list */}
                    Add a queries
                  </button>
                )}
                {/* <div>
                  <button type="submit">Submit</button>
                </div> */}
              </div>
            )}
          />
           <div>
                  <button type="submit">Submit</button>
                </div>
        </Form>
      )}
    />
  </div>
);

export default FriendList;

Здесь я хотел отобразить entityName (запросы >> entity >> entityName), но он не будет отображать этот файл.Как я могу получить доступ к массиву внутри другого массива с помощью Formik?

...