提问人:Hasan 提问时间:10/21/2021 更新时间:10/21/2021 访问量:69
什么是问题 TypeError: action.value is undefined?(反应)
What is Problem TypeError: action.value is undefined? (React)
问:
这是我从 Firebase 表中检索数据的文件。我在这里没有问题。在这里,我记录了控制台以查看所有数据。我的问题出在quiz.js文件中
useQuestion.js
import { getDatabase, ref, query, orderByKey, get } from "firebase/database";
import { useEffect, useState } from "react";
export default function useQuestions(yID) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState();
const [questions, setQuestions] = useState();
useEffect(() => {
// get data from database
async function fetchQuestion() {
const db = getDatabase();
const questionRef = ref(db, "quiz/" + yID + "/questions");
const questionQuery = query(questionRef, orderByKey());
try {
setError(false);
setLoading(true);
const snapshot = await get(questionQuery);
setLoading(false);
if (snapshot.exists()) {
setQuestions((prevQuestions) => {
return [...prevQuestions, ...Object.values(snapshot.val())];
});
}
} catch (e) {
setLoading(false);
console.log(e);
setError("You are Press Wrong Questions.");
}
}
fetchQuestion();
}, [yID]);
return {
loading,
error,
questions,
};
}
这个文件的问题是useReducer。我设置了调度值,但显示 action.value 未定义。为什么我的项目中有这个问题。
quiz.js
import { useEffect, useReducer, useState } from "react";
import useQuestions from "../../hooks/useQuestion";
import { useParams } from "react-router";
import Answare from "../../answare";
import MiniPlayer from "../../miniPlayer";
import PogressBar from "../../pogressBar";
import _ from "lodash";
const initialState = null;
const reducer = (state, action) => {
switch (action.type) {
case "questions":
action.value.forEach((question) => {
question.options.forEach((option) => {
option.checked = false;
});
});
return action.value;
case "answer":
const questions = _.cloneDeep(state);
questions[action.questionID].options[action.optionIndex].checked =
action.value;
return questions;
default:
return state;
}
};
function Quiz() {
const { id } = useParams();
const [currentQuestions, setCurrentQuestions] = useState(0);
const { loading, error, questions } = useQuestions(id);
const [qna, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
dispatch({
type: "questions",
value: questions,
});
}, [questions]);
const handleAnswareChange = (e, index) => {
dispatch({
type: "answer",
QuestionsID: currentQuestions,
optionIndex: index,
value: e.target.checked,
});
};
return (
<>
{loading && <div>Loading.....</div>}
{error && <div>There was a problem.</div>}
{!loading && !error && qna && qna.length > 0 && (
<>
<h1>{qna[currentQuestions].title}</h1>
<h4>Question can have multiple answers</h4>
<Answare
options={qna[currentQuestions].options}
handleChange={handleAnswareChange}
/>
<PogressBar />
<MiniPlayer />
</>
)}
</>
);
}
export default Quiz;
答:
0赞
Moïse Gui
10/21/2021
#1
在我看来,你应该在发送它之前先安慰一下。它可能未定义e.target.checked
评论