0

我正在为决策树制作后退按钮。这棵树是由一个数组和它的索引组成的。现在,yes 或 no 会将它们带到数组索引的不同部分作为响应。我正在尝试找到一种方法来捕获以前的 useState 数组索引,以将它们与 onClick 后退按钮连接起来。

并非所有数组都在这里,只是为了保持简短。

const responses = [
    
    {
      id: 1,
      questionText: "Is the account data entry?",
      answerOptions: [
        { answerText: "No", isCorrect: false },
        { answerText: "Yes", isCorrect: true, jumpToQuestion: 6 },
      ],
      notes: [
      ],
    },
    {
      id: 2,
      questionText: "Is this customer 1 or 2?",
      answerOptions: [
        { answerText: "No", isCorrect: false },
        { answerText: "Yes", isCorrect: true, jumpToQuestion: 7 },
      ],
      notes: [
      ],
    },
    {
      id: 3,
      questionText: "Is the caller",
      answerOptions: [
        { answerText: "Power of Attorney/Conservator", isCorrect: true, jumpToQuestion: 15 },
        { answerText: "Lawyer", isCorrect: true, jumpToQuestion: 13 },
        { answerText: "Emergency Responder", isCorrect: true, jumpToQuestion: 14 },
        { answerText: "Wanting to make a payment", isCorrect: true, jumpToQuestion: 18 },
        { answerText: "Death/Cancellation/Takeover", isCorrect: false, jumpToQuestion: 19},
      ],
      notes: [
      ],
    },
    {
      id: 4,
      questionText: "Is it someone with a signed 'Name Add Form' on file?",
      answerOptions: [
        { answerText: "No", isCorrect: false },
        { answerText: "Yes", isCorrect: true, jumpToQuestion: 7 },
      ],
      notes: [
      ],
    },
    {
      id: 5,
      questionText: "Is it someone who is verbally authorized by a verified account holder to speak with Alder?",
      answerOptions: [
        { answerText: "No", isCorrect: false, jumpToQuestion: 12 },
        { answerText: "Yes", isCorrect: true, jumpToQuestion: 7 },
      ],
      notes: [
      ],
    },

  const [currentQuestion, setCurrentQuestion] = useState(0);

  const handleAnswerButton = (jumpToQuestion) => {
    const nextQuestion = jumpToQuestion || currentQuestion + 1;
    setCurrentQuestion(nextQuestion);
  }
4

1 回答 1

0

只需像使用 jumpToQuestion 一样存储上一个问题 ID。

const [previousQuestionId, setPreviousQuestionId] = useState(0); //Initialize at whatever index you need

然后在你的 handleAnswerButton 中:

const handleAnswerButton = (jumpToQuestion) => {
    setPreviousQuestionId(currentQuestion.id)

    const nextQuestion = jumpToQuestion || currentQuestion + 1;

    setCurrentQuestion(nextQuestion);
  }

让我知道这是否有效:)

于 2020-10-23T20:14:59.670 回答