首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将初始值传递给字段数组并处理窗体值?

如何将初始值传递给字段数组并处理窗体值?
EN

Stack Overflow用户
提问于 2022-10-17 05:16:01
回答 1查看 26关注 0票数 1

我使用可排序容器进行了反应选择,问题是所提取的值是这样的

代码语言:javascript
复制
{
  "fruits": [
    {
      "fruitName": {
        "id": 3,
        "value": "vanilla",
        "label": "Vanilla"
      }
    },
    {
      "fruitName": {
        "id": 1,
        "value": "chocolate",
        "label": "Chocolate"
      }
    }
  ]
} 

如果您注意到每次我选择一个选项时fruitName都是重复的,尽管我不需要它,我只想要它像这样的列表

代码语言:javascript
复制
{
  "fruits": [
    {
      "id": 3,
      "value": "vanilla",
      "label": "Vanilla"
     },
    {
      "id": 1,
      "value": "chocolate",
      "label": "Chocolate"
    }
  ]
}

如果我从字段名中删除fruitName字段,它也不能正常工作,如果我已经选择了水果列表值,那么如何将初始值传递给这个字段

代码语言:javascript
复制
import React from "react";
    import Styles from "./Styles";
    // import { render } from "react-dom";
    import { Form, Field } from "react-final-form";
    import arrayMutators from "final-form-arrays";
    import { FieldArray } from "react-final-form-arrays";
    import {
      SortableContainer,
      SortableElement,
      SortableHandle,
    } from "react-sortable-hoc";
    import Select from "react-select";
    
    const options = [
      { id: 1, value: "chocolate", label: "Chocolate" },
      { id:2, value: "strawberry", label: "Strawberry" },
      { id:3, value: "vanilla", label: "Vanilla" },
    ];
    const DragHandle = SortableHandle(() => (
      <span style={{ cursor: "move" }}>Drag</span>
    ));
    
    const SortableItem = SortableElement(({ name, fields, value }) => (
      <li>
        <DragHandle />
        <Field name={`${name}.fruittName`}>
          {({ input }) => (
            <Select options={options} placeholder="Select Location" {...input} />
          )}
        </Field>
        <span onClick={() => fields.remove(value)} style={{ cursor: "pointer" }}>
          Remove
        </span>
      </li>
    ));
    
    const SortableList = SortableContainer(({ items }) => {
      return (
        <ul>
          {items.map((name, index) => (
            <SortableItem
              key={`item-${index}`}
              index={index}
              value={index}
              name={name}
              fields={items}
            />
          ))}
        </ul>
      );
    });
    
    const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
    
    const onSubmit = async (values) => {
      await sleep(300);
      window.alert(JSON.stringify(values, 0, 2));
    };
    
    const sortEnd =
      (move) =>
      ({ oldIndex, newIndex }) => {
        move(oldIndex, newIndex);
      };
    const Home = () => {
      return (
        <div>
          <Styles>
            <h1>React Final Form - Array Fields</h1>
            <a href="https://github.com/erikras/react-final-form#-react-final-form">
              Read Docs
            </a>
            <Form
              onSubmit={onSubmit}
              mutators={{
                ...arrayMutators,
              }}
              render={({
                handleSubmit,
                form: {
                  mutators: { push, pop },
                },
                pristine,
                reset,
                submitting,
                values,
              }) => {
                return (
                  <form onSubmit={handleSubmit}>
                    <div>
                      <label>Company</label>
                      <Field name="company" component="input" />
                    </div>
    
                    <div className="buttons">
                      <button
                        type="button"
                        onClick={() => push("fruits", undefined)}
                      >
                        Add Customer
                      </button>
                      <button type="button" onClick={() => pop("fruits")}>
                        Remove Customer
                      </button>
                    </div>
                    <FieldArray name="fruits">
                      {({ fields }) => (
                        <SortableList
                          useDragHandle={true}
                          items={fields}
                          onSortEnd={sortEnd(fields.move)}
                        />
                      )}
                    </FieldArray> 
                    <div className="buttons">
                      <button type="submit" disabled={submitting || pristine}>
                        Submit
                      </button>
                      <button
                        type="button"
                        onClick={reset}
                        disabled={submitting || pristine}
                      >
                        Reset
                      </button>
                    </div>
                    <pre>{JSON.stringify(values, 0, 2)}</pre>
                  </form>
                );
              }}
            />
          </Styles>
        </div>
      );
    };
    
    export default Home;
EN

回答 1

Stack Overflow用户

发布于 2022-10-17 05:34:23

这将有助于你的回答,

如果不想重复一个对象/值,就必须过滤掉它。

下面是一个例子,

代码语言:javascript
复制
fruits = [
    {id: 1, name:'Mango'},
    {id: 2, name:'Apple'},
    {id: 3, name:'Orange'}
]

如果您选择的id是2,那么除了2您想要所有其他值,

代码语言:javascript
复制
let selectedId = 2;
let filteredFruitArray = fruits.filter((fruit) => fruit.id !== selectedId);
console.log(filteredFruitArray); //{id: 1, name:'Mango'}{id: 3, name:'Orange'}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74092824

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档