在 React js 中更新对象

问题描述 投票:0回答:1

我在 UI 中遇到一个问题,如果我用短标签(characteristicsValues)编辑特征并更改类型,而不是使用一个短标签,我就会有两个。 这就是UI设计。 enter image description here

这是更改下拉列表中的类型后的预期输出。 enter image description here

这是我当前在更改类型后得到的结果。 enter image description here

这是触发下拉菜单的函数。

function handleCharTypeChange(e, arfId) {
    const type =
      arfId === 'Occupancy'
        ? 'Occupancy'
        : arfId === 'Construction'
        ? 'Construction'
        : e;
    const setTypes = [
      { field: 'characteristicValues', value: type },
      { field: 'characteristicType', value: e },
    ];
    if (e === 'FreeText') {
      setTypes.push({
        field: 'relevantForPricing',
        value: false,
      });
    }
    setTypes.forEach(async (f) => {
      if (f.field === 'characteristicValues') {
        if (state.characteristicValues.length > 0)
          state.characteristicValues.map((v) => {
            let t = { ...v };
            return handleChangeCharacteristicValue(
              t,
              f.value,
              'characteristicValues',
              'type'
            );
          });
      } else handleChangeCharacteristic(f.field, f.value);
    });
  }

我认为根本原因是没有正确清除现有的特征值。因为当我尝试在范围类型下添加另一个短标签并将其更改为 FreeText 时,它返回三个。我尝试添加三元运算符。

const setTypes = [
      { field: 'characteristicValues', value: type === 'FreeText' ? [] : type },
      { field: 'characteristicType', value: e },
    ];

但是问题仍然发生,我也尝试传递空数组。

if (e === 'FreeText') {
      setTypes.push({
        field: 'characteristicValues',
        value: [],
      });
      setTypes.push({
        field: 'relevantForPricing',
        value: false,
      });
    }

但是问题仍然出现。它仍然返回两个短标签。如果你问我任何有关 React js 的问题,请注意。抱歉我真的没有处理这件事的背景和经验。我还在学习。我将不胜感激任何帮助和我可以获得的一些新知识。谢谢!

javascript reactjs state
1个回答
0
投票
async function handleCharTypeChange(e, arfId) {
  const type =
    arfId === 'Occupancy'
      ? 'Occupancy'
      : arfId === 'Construction'
      ? 'Construction'
      : e;

  const setTypes = [
    { field: 'characteristicValues', value: type === 'FreeText' ? [] : type },
    { field: 'characteristicType', value: e },
  ];

  if (e === 'FreeText') {
    setTypes.push({
      field: 'relevantForPricing',
      value: false,
    });
  }

  for (const f of setTypes) {
    if (f.field === 'characteristicValues' && state.characteristicValues.length > 0) {
      for (const v of state.characteristicValues) {
        let t = { ...v };
        await handleChangeCharacteristicValue(t, f.value, 'characteristicValues', 'type');
      }
    } else {
      handleChangeCharacteristic(f.field, f.value);
    }
  }
}

确保handleChangeCharacteristic和handleChangeCharacteristicValue函数也正确处理异步操作。

if (e === 'FreeText') {
  setTypes.push({
    field: 'characteristicValues',
    value: [],
  });
  setTypes.push({
    field: 'relevantForPricing',
    value: false,
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.