gpt4 book ai didi

javascript - 在句柄函数上 react 钩子(Hook)状态未定义

转载 作者:行者123 更新时间:2023-12-04 10:03:58 25 4
gpt4 key购买 nike

我正在创建一个具有持久响应状态的简单测验,我目前正试图弄清楚为什么在我的 handleAnswerClick 函数中未定义 responseState ,如果每次点击都会触发此函数。到那时,所有状态都应该设置好了。

const Question: React.FC<IProps> = (props) => {
const [responseState, setResponseState] = useState([]);
const [question, setQuestion] = useState<IStateProps>(props.id);
const [answers, setAnswers] = useState([]);
const [choice, setChoice] = useState();

const initialResponseState = () => {
const data = {
duration: '00:01:00',
examTakerProgress: 1,
question: props.id,
answer: '1',
}
axios.post(`${host}/api/responseState/`, data)
.then(() => {
console.log('Created the initial Response State');
})
.catch((err) => {
console.log(err);
})
}

const getData = async () => {
await axios.all([
axios.get(`${host}/api/question/${question}`),
axios.get(`${host}/api/responseState/examTakerProgress/1/question/${props.id}`)
])
.then(axios.spread((questionData, responseData) => {
if (!responseData.data.length > 0) {
initialResponseState();
}
setResponseState(responseData.data);
setQuestion(questionData.data);
setAnswers(questionData.data.answers);
setChoice(responseData.data.length > 0 ? responseData.data[0].answer : '');
setTimeout(() => {
props.toggleLoading();
}, 50);

}))
.catch(err => console.error(err));
};

useEffect(() => {
getData()
}, [])


const handleAnswerClick = async (number: number) => {
setChoice(number);
const data = {
duration: '00:01:00',
examTakerProgress: 1,
question: props.id,
answer: number,
}
await axios.put(`${host}/api/responseState/${responseState[0].id}/`, data)
.then((data) => {
console.log(data);
console.log('choice changed to :' + number);
})
.catch((err) => {
console.log(err);
})
}

if (props.loading) {
return <Loader/>
}

return (
<React.Fragment>
<h3>{question.label}</h3>
<p className='mb-3'>{question.description}</p>
<ListGroup as="ul">
{answers.map((answer, index) => {
if (answer.id === choice) {
return <ListGroup.Item key={answer.id} action active> <Answer key={index}
answer={answer}/></ListGroup.Item>

} else {
return <ListGroup.Item key={answer.id} action onClick={() => {
handleAnswerClick(answer.id)
}}><Answer key={index}
answer={answer}/></ListGroup.Item>
}
}
)}
</ListGroup>
</React.Fragment>
)};

有人可以解释一下为什么会这样吗?

最佳答案

基于这条线
const [responseState, setResponseState] = useState({}); ,
responseState是一个对象。

但在 handleAnswerClick函数,您将其用作数组 ${responseState[0].id} .

请注意,如果对象具有 0,这实际上是有效的。关键,但因为你得到未定义的情况并非如此。

关于javascript - 在句柄函数上 react 钩子(Hook)状态未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61684486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com