[英]Uncaught TypeError: Cannot read properties of undefined (reading 'undefined')
我正在尝试更改单击时使用 useState 挂钩创建的 state。 但我不明白这个错误。 未捕获的类型错误:无法读取未定义的属性(读取“未定义”)。 我不明白为什么在 setState (state.activeQuestion + 1) 之后会发生这种情况
import React, {useState} from 'react'
import classes from './Quiz.module.css'
import ActiveQuiz from '../../components/ActiveQuiz/ActiveQuiz'
export default function Quiz () {
const [state, setState] = useState(
{ activeQuestion: 0,
quiz: [
{
question: 'Якого коліру небо',
rightAnswerId: 2,
id: 1,
answers: [
{text: 'чорний', id: 1},
{text: 'синій', id: 2},
{text: 'червоний', id: 3},
{text: 'зелений', id: 4}
]
},
{
question: 'Якому році 2 світова',
rightAnswerId: 3,
id: 2,
answers: [
{text: '1954', id: 1},
{text: '1948', id: 2},
{text: '1949', id: 3},
{text: '1918', id: 4}
]
}
],}
)
const onAnswerClickHandler = answerId => {
console.log('Answer Id: ', answerId);
setState(state.activeQuestion + 1)
}
return(
<div className={classes.Quiz}>
<div className={classes.QuizWraper}>
<h1> Дайте відповідь на всі Питання </h1>
<ActiveQuiz
answers={state.quiz[state.activeQuestion].answers}
question={state.quiz[state.activeQuestion].question}
onAnswerClick={onAnswerClickHandler}
quizLength={state.quiz.length}
answerNumber={state.activeQuestion + 1}
/>
</div>
</div>
)
}
在您的代码中,您正在使用 onAnswerClickHandler 更改 state 的形状。 您的 state 是 object 并具有不同的值。
const onAnswerClickHandler = answerId => {
console.log('Answer Id: ', answerId);
setState(state.activeQuestion + 1)
}
在这里,您将 state 更改为一个数字:
state = {object stuff here}//
//after you call the function
state = 0 + 1 // all the other stuff is gone
正如@cybercoder 评论的那样,您应该使用扩展运算符:
setState(prev=>({...state, activeQuestion : prev.activeQuestion + 1})) –
使用扩展运算符,您可以复制 object 包含的所有数据,并且只更新要更新的必要值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.