Как очистить массив полей в избыточной форме - PullRequest
0 голосов
/ 22 мая 2019

Я пытаюсь очистить массив флажков в массиве полей из избыточной формы. Как я могу это сделать?

Я использую избыточную форму FieldArray в формате members:[filterOption:{}, checkBoxOption:{}]. Значение checkBoxOption зависит от выпадающего списка filterOption. Всякий раз, когда пользователь выбирает параметр из filterOption, в результате он получает список флажков, из которых он должен выбрать из списка checkBoxOption.

redux store

Скажем, если пользователь выбрал значение из filterOption и checkBoxOption, а теперь он меняет значение filterOption, в результате он получит новый список массива для checkBoxOption. Значения заменяются новыми, но они не снимаются.

Я могу очистить массив флажков в массиве значений с помощью fields.get(event).checkBoxOption = {}, но не могу найти решение о том, как очистить массив полей.

Может кто-нибудь помочь мне с этим?

<ul className="list-group">
      {
        fields.map((member, index) => (
          <li className="list-group filter-select-box" key={index}>
            <SelectBox
              name={`${member}.filterOption`}
              label="Metadata Attribute"
              options={attributes.map(attribute => ({
                value: attribute.name,
                label: attribute.name,
                disabled: selectedAttributes.filter(value => value.name === attribute.name).length > 0,
              }))}
              isChange
              handleSelectChange={opt => handleOptionChange(index, opt.value)}
            />
            {checkStatus(index) && (
              <div className="select-checkbox-option form-group">
                {
                  getCheckboxList(index).map((checkboxItem, x) => (
                    <CheckBox
                       key={x}
                       type="checkbox"
                       name={`${member}.checkBoxOption.${checkboxItem}`}
                       label={checkboxItem}
                       value={`${member}.checkBoxOption.${checkboxItem}`}
                       id={checkboxItem}
                    />
                  ))
                }
              </div>
            )}
          </li>
        ))
      }
      <li className="list-group filter-select-box">
        <button className="add-filter" type="button" onClick={() => fields.push({})}>
          <img src={filterPlus} alt="" className="filterPlus" />
          Add Filter
        </button>
        {touched && error && <span>{error}</span>}
      </li>
    </ul>

функция, которая получает значение флажка

const handleOptionChange = (event, nameAttribute) => {
    const value = {
      index: event,
      status: true,
      name: nameAttribute,
    };

    let selectedAttributesStatus = false;
    for (let i = 0; i < selectedAttributes.length; i += 1) {
      if (value.index === selectedAttributes[i].index) {
        selectedAttributes[i].name = value.name;
        selectedAttributesStatus = true;
      }
    }

    if (!selectedAttributes.length || !selectedAttributesStatus) {
      setSelectedAttributes([...selectedAttributes, value]);
    }

    setShowOptions([...showOption, value]);
    getCategoricalVar(extractorId, nameAttribute)
      .then((resp) => {
        const newAttributeValue = {
          index: event,
          value: resp,
        };
        fields.get(event).checkBoxOption = {};
        setSelectedIndex(false);
        console.log('fields.get(event).checkBoxOption: ', fields.get(event).checkBoxOption);
        let attributeValuesStatus = false;
        for (let i = 0; i < attributeValues.length; i += 1) {
          if (newAttributeValue.index === attributeValues[i].index) {
            attributeValues[i].value = newAttributeValue.value;
            attributeValuesStatus = true;
          }
        }
        if (!attributeValues.length || !attributeValuesStatus) {
          setAttributeValues([...attributeValues, newAttributeValue]);
        }
      })
      .catch(printError);
  };

Функция, которая устанавливает значение на флажок

const getCheckboxList = (index) => {
    for (let i = 0; i < attributeValues.length; i += 1) {
      if (attributeValues[i].index === index) {
        return attributeValues[i].value;
      }
    }
    return [];
  };
...