0

我正在 react.js 中创建测验应用程序。问题:如何将总分不仅增加 1,而且增加 3、4(每个答案应该有唯一的分数)题库:let qBank = [ { 问题:“我计划开始从我的投资中提取资金:”,选项: ["不到3年", "3-5年", "6-10年", "11年以上"], answer:"3-5年", id:"0" }, {问题: “一旦我开始从投资中提取资金,我计划将所有资金用于:”,选项:[“少于 2 年”、“2-5 年”、“6-10 年”、“11 年或more"], answer:"2-5 years", id:"1" }, { question: "我将我的投资知识描述为:", options: ["None", "Limited", "Good", "

ETC

和代码本身:

nextQuestionHandler = () => {

    const { userAnswer, answers, score } = this.state;
    this.setState({
        currentQuestion: this.state.currentQuestion + 1
    })
    //increment the score if answer is correct
    if (userAnswer === answers) {
        this.setState({
            score: score + 1
        })
    }
}

//update the component
componentDidUpdate(prevProps, prevState) {
    const { currentQuestion } = this.state;
    if (this.state.currentQuestion !== prevState.currentQuestion) {
        this.setState(() => {
            return {
                disabled: true,
                questions: qBank[currentQuestion].question,
                options: qBank[currentQuestion].options,
                answers: qBank[currentQuestion].answer
            };
        })
    }
}
4

2 回答 2

1

您可以为每个问题添加一个额外的属性。

例如。

{ question: "I would describe my knowledge of investments as:", options: ["None", "Limited", "Good", "Extensive"], answer:"None", id:"2", value: 3 } 

然后更新分数:

if (userAnswer === answers) {
        this.setState({
            score: score + currentQuestion.value
    })
}
于 2020-06-19T14:57:32.543 回答
0

为存储在 中的问题添加一个value属性qBank

let qBank = [ 
  { 
    question: "I plan to begin withdrawing money from my investments in:", 
    options: ["Less than 3 years", "3-5 years", "6-10 years", "11 years or more"], 
    answer:"3-5 years", 
    value: 1,
    id:"0" 
  }, 
  { 
    question: "Once I begin withdrawing funds from my investments, I plan to spend all of the funds in:", 
    options: ["Less than 2 years", "2-5 years", "6-10 years", "11 years or more"], 
    answer:"2-5 years", 
    value: 2,
    id:"1" 
  }, 
  { question: "I would describe my knowledge of investments as:", 
    options: ["None", "Limited", "Good", "Extensive"], 
    answer:"None", 
    value: 3,
    id:"2" 
  }
]

nextQuestionHandler = () => {

    const { userAnswer, answers, score, value } = this.state;
    this.setState({
        currentQuestion: this.state.currentQuestion + 1
    })
    //increment the score if answer is correct
    if (userAnswer === answers) {
        this.setState({
            score: score + value
        })
    }
}

于 2020-06-19T14:59:56.393 回答