javascript - 我想添加一个功能,如果我回答所有 5 个问题,页面应该重定向到另一个 url ( /result ) 以显示结果
问题描述
我想添加一个功能,如果我回答所有 5 个问题,页面应该重定向到另一个 url ( /result ) 以立即显示结果它只是使用 css 来覆盖问题并在所有 5 个问题都得到回答后显示结果这里是代码:
index.js
import React, { Component } from "react";
import ReactDom from "react-dom";
import "./assets/style.css";
import QuestionBox from "./components/QuestionBox";
import Result from "./components/Result";
import quizService from "./quizService";
class QuizBee extends Component {
state = {
questionBank: [],
score: 0,
responses: 0,
};
getQuestions = () => {
quizService().then((question) => {
this.setState({
questionBank: question,
});
});
};
computeAnswer = (answer, correctAnswer) => {
if (answer === correctAnswer) {
this.setState({
score: this.state.score + 1,
});
}
this.setState({
responses: this.state.responses < 5 ? this.state.responses + 1 : 5,
});
};
playAgain = () => {
this.getQuestions();
this.setState({
score: 0,
responses: 0,
});
};
componentDidMount() {
this.getQuestions();
}
render() {
return (
<div className="container">
<div className="title">QuizBee</div>
{this.state.questionBank.length > 0 &&
this.state.responses < 5 &&
this.state.questionBank.map(
({ question, answers, correct, questionId }) => (
<QuestionBox
question={question}
options={answers}
key={questionId}
selected={(answer) => this.computeAnswer(answer, correct)}
/>
)
)}
{this.state.responses === 5 ? (
<Result score={this.state.score} playAgain={this.playAgain} />
) : null}
</div>
);
}
}
ReactDom.render(<QuizBee />, document.getElementById("root"));
QuestionBox.js
import React, { useState, useEffect } from "react";
const QuestionBox = ({ question, options, selected }) => {
const [answer, setAnswer] = useState(options);
const [disable, setDisable] = useState(false);
return (
<div className="questionBox">
<div className="question">{question}</div>
{answer.map((text, index) => (
<button
key={index}
disabled={disable}
className="answerBtn"
onClick={() => {
setAnswer([text]);
selected(text);
setDisable(true);
}}
>
{text}
</button>
))}
</div>
);
};
export default QuestionBox;
结果.js
import React from "react";
const Result = ({ score, playAgain }) => {
return (
<div className="score-board">
<div className="score">You Scored {score} / 5 correct answers! </div>
<button className="playBtn" onClick={playAgain}>
Play again!
</button>
</div>
);
};
export default Result;
我希望一旦回答了所有 5 个问题,页面应该重定向到结果页面,而无需单击任何按钮,只需回答所有 5 个问题。我尝试了反应路由器购买无法正确完成我从早上开始就一直在尝试请任何帮助将不胜感激
解决方案
推荐阅读
- python - pandas 数据框的某些标头显示为属性,但在 VSCode 中的“调试”>“变量”中没有全部显示
- php - 成功登录亚马逊账户授权后,亚马逊支付出现“AccessDenied”错误
- typescript - 带有 typescript 的 React 路由器 v5 上所需的 url 参数,可以是未定义的
- javascript - 如何在Vue中为v-for创建的每个按钮组设置accesskey?
- azure - Azure IoT Hub - 检查端口 5671 是否打开
- php - 如何从 laravel 控制器传递嵌套的 foreach 以在刀片上查看
- apache-kafka - 是否可以启用或禁用特定的 JMX 指标以使用 Jconsole 监控 Kafka 集群
- reactjs - 学习 Redux + react-redux 的一些问题
- php - 我想在 laravel 查询中进行 mysqli 查询。时间计数
- tomcat - 代理 IIS 服务器到 Tomcat 应用程序