微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用数组索引的先前状态创建后退按钮

如何解决使用数组索引的先前状态创建后退按钮

我正在为决策树做一个后退按钮。该树由数组及其索引组成。现在,是或否将把它们带到数组索引的不同部分作为响应。我试图找到一种捕获以前的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?",jumpToQuestion: 7 },{
      id: 3,questionText: "Is the caller",answerOptions: [
        { answerText: "Power of Attorney/Conservator",jumpToQuestion: 15 },{ answerText: "Lawyer",jumpToQuestion: 13 },{ answerText: "Emergency Responder",jumpToQuestion: 14 },{ answerText: "Wanting to make a payment",jumpToQuestion: 18 },{ answerText: "Death/Cancellation/Takeover",isCorrect: false,jumpToQuestion: 19},{
      id: 4,questionText: "Is it someone with a signed 'Name Add Form' on file?",{
      id: 5,questionText: "Is it someone who is verbally authorized by a verified account holder to speak with Alder?",jumpToQuestion: 12 },const [currentQuestion,setCurrentQuestion] = useState(0);

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

解决方法

就像存储对jumpToQuestion一样,只需存储先前的问题ID。

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

然后在您的句柄中AnswerButton:

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

    const nextQuestion = jumpToQuestion || currentQuestion + 1;

    setCurrentQuestion(nextQuestion);
  }

让我知道是否可行:)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。