React 表单 UI 未正确反映状态变化

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

我正在 React 中开发一个嵌套表单,其中用户可以有多个表单,每个表单可以有多个部分,每个部分可以有多个下拉菜单。我面临的问题是,删除特定下拉列表会正确更新状态,但不会反映在 UI 中删除的正确下拉列表。

我有这些状态

const [addConditions, setAddConditions] = useState([[]]);
const {formIndex} = useContext(FormContext);
const [addConditions, setAddConditions] = useState([[]]);
const { formIndex } = useContext(FormContext);
const [eventValues, setEventValues] = useState([{
    // ...other properties
    conditions: [{ locked: [] }],
    // ...
}]);

添加部分

const addSection = () => {
    setAddConditions(prev => [...prev, [""]])
}

添加下拉菜单

const addDropdownToSection = (sectionIndex) => {
    setAddConditions(prev => {
        const updated = [...prev];
        updated[sectionIndex].push("");
        return updated;
    });
}

我将下拉值存储在 eventValues 中

const handlePropertyInputChange = (outerIndex, innerIndex, stateType="locked", e) => {
        setEventValues(prevValues => {
            let updatedEvents = [...prevValues];
            let updatedConditions = [...updatedEvents[formIndex].conditions];

            if (!updatedConditions[outerIndex]) {
                updatedConditions[outerIndex] = { locked: [] };
            }
            const { name, value } = extractValue(e);
            updatedConditions[outerIndex][stateType][innerIndex] = {
                ...updatedConditions[outerIndex][stateType][innerIndex],
                [name]: value,
            };
            updatedEvents[formIndex].conditions = updatedConditions;
            return updatedEvents;
        });
    };

当我必须删除特定下拉列表时出现问题

const removePropertyFromCondition = (sectionIndex, propertyIndex) => {
    setEventValues(prevValues => {
        let updateEvents = makeDeepCopy(prevValues)
        let updatedConditions = [...updateEvents[formIndex].conditions];
        updatedConditions[sectionIndex].locked.splice(propertyIndex, 1);
        updateEvents[formIndex].conditions = updatedConditions;
        console.log({updateEvents})
        return updateEvents
    });
    setAddConditions(prev => {
        const updated = makeDeepCopy(prev)
        updated[sectionIndex].splice(propertyIndex, 1);
        return updated;
    });
};

调用

removePropertyFromCondition
时,eventValues 状态已正确更新(如控制台中所示),但在 UI 中,它始终是被删除部分中的最后一个下拉列表,而不是我想要的那个。此后,与下拉值的任何交互都会导致应用程序崩溃。

如何确保在 UI 中删除正确的下拉列表?

我尝试为每个部分分配一个唯一的标识符来解决该问题,但这种方法并没有解决问题。

任何帮助表示赞赏,谢谢

react-hooks nested setstate react-state react-state-management
1个回答
1
投票

由于密钥不稳定而出现问题。我使用数组索引作为映射

<div/>
的键,但是当添加或删除元素时它们会发生变化。 我使用 UUID 作为稳定标识符。

{eventValues.conditions.map((propertyConditions, outerIndex) => {
    return (
        <div key={propertyConditions.UUID}>
            {propertyConditions.locked.map((propertyCondition, innerIndex) => {
                return (
                    <div key={propertyCondition.UUID}>
                    </div>
                )
            })}
        </div>
    )
})}
© www.soinside.com 2019 - 2024. All rights reserved.