Arrays 使用数组索引的上一个状态制作后退按钮
我正在做一个决策树的后退按钮。树由数组及其索引组成。现在,是或否将把它们作为响应带到数组索引的不同部分。我试图找到一种方法来捕获以前的useState数组索引,并使用onClick back按钮将它们连接起来 并不是所有的数组都在这里,只是为了保持简短Arrays 使用数组索引的上一个状态制作后退按钮,arrays,reactjs,use-state,array-indexing,Arrays,Reactjs,Use State,Array Indexing,我正在做一个决策树的后退按钮。树由数组及其索引组成。现在,是或否将把它们作为响应带到数组索引的不同部分。我试图找到一种方法来捕获以前的useState数组索引,并使用onClick back按钮将它们连接起来 并不是所有的数组都在这里,只是为了保持简短 const responses = [ { id: 1, questionText: "Is the account data entry?", answerOptions
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);
}
只需存储上一个问题id,就像处理JumpTo问题一样
const [previousQuestionId, setPreviousQuestionId] = useState(0); //Initialize at whatever index you need
然后在你的手上按一下按钮:
const handleAnswerButton = (jumpToQuestion) => {
setPreviousQuestionId(currentQuestion.id)
const nextQuestion = jumpToQuestion || currentQuestion + 1;
setCurrentQuestion(nextQuestion);
}
让我知道这是否有效:)