Estoy tratando de configurar el estado dentro de un método, tengo un sistema de votación simple (Sí o No) si hace clic en Sí , el estado debe estar arriba y si hace clic en No , el estado debe estar abajo
Tengo problemas para fusionar el método voteHandler y setVote
Aquí está mi componente:
import React, { useState, useContext } from 'react'; import {AnswerContext} from './AnswerWrapper'; const AnswerItem = (props) => { let indexPlus; const indexCount = (index) => { indexPlus = index; return indexPlus; } const { active, setActive } = useContext(AnswerContext) const [vote, setVote] = useState(); const voteHandler = (e, index) => { e.preventDefault(); setActive(index); setVote(""); // this might be "up" or "down" // I am sending this to a parent component props.onVote ({ vote : vote, answerID : index }) } return ( <div> <button onClick={(e) => voteHandler(e, props.index)}>Yes <span>({props.ups !== null ? props.ups : 0 })</span></button> <button onClick={(e) => voteHandler(e, props.index)}>No <span>({props.downs !== null ? props.downs : 0 })</span></button> </div> ) } export default AnswerItem;Puede enviar el valor cuando vincula el onClick :
<button onClick={(e) => voteHandler(e, props.index, 'up')}>Yes <span>({props.ups !== null ? props.ups : 0 })</span></button> <button onClick={(e) => voteHandler(e, props.index, 'down')}>No <span>({props.downs !== null ? props.downs : 0 })</span></button> Y usa eso en tu voteHandler :
const voteHandler = (e, index, value) => { e.preventDefault(); setActive(index); setVote(value); // this might be "up" or "down" // I am sending this to a parent component props.onVote ({ vote : vote, answerID : index }) }Cuando tu lo hagas:
setVote(value); // this might be "up" or "down" // I am sending this to a parent component props.onVote ({ vote : vote, answerID : index }) No obtendrá el vote actualizado ya que setState es asíncrono. Si desea llamar a props.onVote en cada vote y cambio active , use useEffect :
const AnswerItem = (props) => { let indexPlus; const indexCount = (index) => { indexPlus = index; return indexPlus; } const { active, setActive } = useContext(AnswerContext) const [vote, setVote] = useState(); useEffect(() => { props.onVote ({ vote : vote, answerID : active }) }, [vote, active]) const voteHandler = (e, index) => { e.preventDefault(); setActive(index); setVote(""); } return ( <div> <button onClick={(e) => voteHandler(e, props.index)}>Yes <span>({props.ups !== null ? props.ups : 0 })</span></button> <button onClick={(e) => voteHandler(e, props.index)}>No <span>({props.downs !== null ? props.downs : 0 })</span></button> </div> ) }