Редактирование массива в состоянии добавляет новый элемент вместо обновления существующего (реагирует JS) - PullRequest
0 голосов
/ 02 ноября 2019

У меня странная проблема с состоянием штата, и я не могу понять, почему это происходит.

У меня есть функция для обработки ввода формы для выборов, и я хочу обновить существующий выбор новым значением, предоставленным пользователем в поле ввода.

Я придумал функцию, которая работает, но вместо того, чтобы просто редактировать существующую строку, она также добавляет новую строку в массив с обновленным значением. Очевидно, это не то, что мне нужно, я просто хочу, чтобы массив возвращался с обновленными исходными данными.

Ниже моя функция:

const handleSelectionInput = (e) => {
    // set id of the input being edited
    const id = e.target.id;

    // the id consists of 3 parts, 1 = the index of the breakout array
    // 2 = the index of the selection list array
    // 3 = whether its the name of the selection or the capacitiy ex: 0_0_key
    let breakoutIndex = parseInt(id.slice(0, id.indexOf("_")));
    let selectionIndex = parseInt(id.slice(id.indexOf("_") + 1, id.lastIndexOf('_')));
    let updateValue = id.slice(id.lastIndexOf("_") + 1, -1);
    console.log(breakoutRow[breakoutIndex]);

    // get the breakout associated wtih the selections
    let allBreakouts = breakoutRow;
    let currentBreakout = allBreakouts[breakoutIndex];
    currentBreakout["selection"][selectionIndex].key = e.target.value;
    allBreakouts[breakoutIndex] = currentBreakout;
    // if value is key update the state of the input fields

    console.log(allBreakouts);
    if (updateValue === "ke") {
        setBreakoutRow(prevBreakouts => (
             // this returns the updated value but also adds to the array?
            [...prevBreakouts, prevBreakouts[breakoutIndex] = currentBreakout]
        )

        );
    }
    console.log(breakoutRow);

}

Как бы я мог просто вернутьобновленный массив и не добавить новый элемент к нему?

1 Ответ

0 голосов
/ 02 ноября 2019

Глупый я, мне нужно было сопоставить существующие поля и обновить их там:

if (updateValue === "ke") {
        setBreakoutRow(prevBreakouts => (prevBreakouts.map((breakout, index) => {
            console.log(prevBreakouts.indexOf());
            if (prevBreakouts.indexOf() === breakoutIndex) {
                return currentBreakout;
            }
            return breakout;
        })
        )

        );
    }
...