Я изо всех сил пытался сбросить состояние функции handleSubmit. Есть 3 вопроса, которые приходят один за другим, и при отправке следующие 3 вопроса должны прийти, например, 1/3, 2/3 и 3/3, и этот процесс продолжается до тех пор, пока все вопросы не будут отправлены. Вот код ниже:
const Quiz = () => {
const { questions, quiz, options } = useSelector((state) => state.quiz);
const [currentQuestion, setCurrentQuestion] = useState(0);
console.info(currentQuestion[number] + "1q");
const dispatch = useDispatch();
const history = useHistory();
const location = useLocation();
const classes = useStyles();
// this is to get the questions from the history coming from redux store.
useEffect(() => {
if (!questions) {
dispatch(fetchQuestions(history));
}
}, []);
const handleRadioChange = (number, event) => {
let currentSelection = questions.find(question => question.number === number);
console.info(currentSelection + "radio selected");
currentSelection.value = event.target.value;
console.info(currentSelection.value + "calculate score");
// Set the new question count based on the current one
setCurrentQuestion((current) => {
return Math.min(
current + 1,
questions.length - 1
);
});
};
const handleSubmit = (event) => {
event.preventDefault();
const valid = questions.some((q) => !q.value);
console.info(valid + "questionsalpha");
if (!valid) {
dispatch(postQuiz({ responses: questions, id: quiz.id }, history));
}
// this i added to get the question process repeat as earlier, but not working.
setCurrentQuestion((current) => {
return Math.min(
current + 1,
questions.length - 1
);
});
};
return (
!questions?.length ? <CircularProgress /> : (
<Grid className = {classes.container} container alignItems = "stretch" spacing = {1}>
<form onSubmit = {handleSubmit}>
{/* Only show the question if it's index is less than or equal to the current question */}
{questions.map((question, index) => {return index <= currentQuestion ? (
<FormControl component = "fieldset" key = {question.number} className = {classes.formControl} data-hidden = {question.number !== current_question[question.number]}>
<FormLabel component = "legend">{question.question}</FormLabel>
<RadioGroup aria-label = "quiz" name = "quiz" value = {question.value} onChange = {(e) => handleRadioChange(question.number, e)}>
{options.map((option) =>
<FormControlLabel key = {option.score} value = {option.score} control = {<Radio />} label = {option.label} />
)}
</RadioGroup>
</FormControl>
) : null})}
<Button type = "submit" variant = "outlined" color = "primary" className = {classes.button}>
Submit
</Button>
</form>
</Grid>
)
);
};
export default Quiz;
Когда пользователь отправил форму, вопрос должен появляться один за другим, и если пользователь обновляет страницу между ними, она должна показывать ту же страницу, с которой он ушел, а не новый URL-адрес. Пожалуйста помоги
Ваш handleSubmit
должен сбросить состояние до 0:
const handleSubmit = (event) => {
event.preventDefault();
const valid = questions.some((q) => !q.value);
console.info(valid + "questionsalpha");
if (!valid) {
dispatch(postQuiz({ responses: questions, id: quiz.id }, history));
}
// Reset to zero, and let handleRadioChange increase it
setCurrentQuestion(0);
};
```
Еще одна вещь @Tom, когда страница перезагружается, она переходит к следующему URL-адресу, где отображается оценка без заполнения вопросов и ответов. Любая идея, почему это происходит?
Вы не показали ничего общего с оценкой или всей страницей, поэтому я не могу знать, что происходит.
он переходит на следующую страницу при обновлении страницы, а не на той же странице. Я думаю, что проблема связана с setCurrentQuestion на кнопке дескриптора, поскольку в URL-адресе отображается локальный: 3000/викторина?викторина=2 (здесь второй тест берется из имени группы RadioButon)
при повторном входе в систему пользователь должен быть на странице викторины, если он не завершен, но он перенаправлен на последнюю страницу. Я думаю, что проблема с вопросами. Длина может быть не читается. или что-то другое, я не могу понять, я переместил questions.length, но все та же проблема
Я решил проблему. Спасибо за то, что вы были так добры и помогли мне с проблемой, с которой я столкнулся. useEffect(() => { if (!questions) { dispatch(fetchQuestions(история)); } }, []); в этих строках просто убраны пустые скобки все работает. Спасибо
@ Том, пожалуйста, проверь это