@MarEeeeee

Почему не обновляется состояние checkbox?

Как правильно обновлять state для массива объектов?

Инициализация объектов:

type Result = number
interface Answer {
    result: Result[]
}
const answers: Answer[] = [];

questions.forEach(()=>{ 
    answers.push({      
        result:[]
    });
})

Массив answers выглядит так:

[{result:[]},{result:[]},{result:[]},{result:[]}]

Создание хука:

const [currentAnswer, setNewAnswer] = useState<Answer[]>(answers);

То что я уже пробовал:

1) Состояние перезаписывается, но мой элемент не перерисовывается

currentAnswer[currentQuestion].result.push(Number(e.target.id));
 setNewAnswer(currentAnswer);

2)

let newValue = currentAnswer[currentQuestion].result;
        newValue.push(Number(e.target.id));
        console.log(newValue)
        setNewAnswer({...currentAnswer[currentQuestion], newValue}) //ругается на тип newValue

/Argument of type '{ newValue: number[]; result: number[]; }' is not assignable to parameter of type 'SetStateAction<Answer[]>'.
  Object literal may only specify known properties, and 'newValue' does not exist in type 'SetStateAction<Answer[]>'

Как правильно записать новые значения в соответствующий объект в свойство result?

Код всего компонента.
  • Вопрос задан
  • 112 просмотров
Решения вопроса 1
@MarEeeeee Автор вопроса
Требовалось создать клон существующего массива, добавить в него новые элементы, а уже потом использовать setState()
let newAnswer = [...currentAnswer];
newAnswer[currentQuestion].result.push(parseInt(e.target.id));
setNewAnswer(newAnswer);
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы