javascript - Why is this variable reassigned to 0? -
i have react component takes in array, , renders components using map()
. issue index
value map()
seems revert 0 no matter in anonymous function associated onchange
listener.
function questions({ questions, answers, toggleanswers }) { const questionbuttons = questions.map((question, index) => { if (answers[index - 1] === undefined || answers[index - 1] === 'true') { const buttonindex = index; console.log('before return etv:', event.target.value, 'index:', index, 'buttonindex:', buttonindex); return ( <customformcomponent key={ index } name={ question.substr(0,5) } label={ question } value={ answers[index] } handlechange={ (event) => { console.log('isthisever not zero?', buttonindex); toggleanswers(event, index); } } /> ); } else { return null; } }); return ( <div> { questionbuttons } </div> ); }
the punchline? it's never not zero. initial render , console output:
before return etv: undefined index: 0 buttonindex: 0
and after tapping 'yes' button:
isthisever not zero? 0 before return etv: true index: 0 buttonindex: 0 before return etv: true index: 1 buttonindex: 1 isthisever not zero? 0 before return etv: true index: 0 buttonindex: 0 before return etv: true index: 1 buttonindex: 1
if tap on either of "no" buttons, buttonindex
still equals 0.
Comments
Post a Comment