Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
setState no funciona como se esperaba. Toma el estado inicial cada vez que

Así que tengo este fragmento de código, donde tengo que actualizar el estado y llamar a la API cada vez que se hace clic en el botón. La primera vez funciona como se esperaba, pero la próxima vez establece la hora de finalización en la hora inicial y establece la hora de inicio con 2 horas antes de lo esperado. El registro de mi consola funciona perfectamente, pero hay algunos problemas mientras intento configurar el estado. Intenté agregar una función de devolución de llamada después de cada setState y también intenté configurar el estado después del final de if-else, pero no me muestra el resultado requerido.

 class ButtonComponent extends Component{ constructor(props) { super(props); this.state = { timeData: { endTime: moment(), startTime: moment().subtract(2, 'h'), }, dropdownOption: '2HOURS' } this.callAPI= this.callAPI.bind(this); } componentDidMount() { if (this.state.dropdownOption=== '2HOURS') { this.callAPI(); } } onClick(){ let time = {...this.state.timeData}; let option; option = this.state.dropdownOption; if(option === '10hours'){ time['endTime'] =timeData['startTime']; console.log('endTime', timeData['endTime']) time['startTime'] = timeData['endTime'].subtract(10, 'h'); console.log('startTime', time['startTime']) this.setState({timeData: time}, this.callAPI()) } } } }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

No estoy seguro de entender lo que quiere hacer, pero debe tener cuidado con el hecho de que setState es asíncrono, por lo que si llama a callAPI el mismo momento en que llama a setState , es normal que callAPI no obtenga el estado actualizado. (Creo que entiendo que esta es la forma en que está tratando de usar su callAPI ).

Aquí hay una sugerencia de implementación, al menos para que quede más claro:

 class ButtonComponent extends Component{ constructor(props) { super(props); this.state = { timeData: { endTime: moment(), startTime: moment().subtract(2, 'h'), }, dropdownOption: '2HOURS', }; this.callAPI= this.callAPI.bind(this); } componentDidMount() { if (this.state.dropdownOption=== '2HOURS') { this.callAPI(); } } callAPI() { console.log("updated state", this.state.timedata) } onClick() { const timeData = {...this.state.timeData}; const option = this.state.dropdownOption; if(option === '10hours') { // I quite don't get the way you want to update your state so this might need to be adapted. timeData.endTime = timeData.startTime; timeData.startTime = moment(); // this.callAPI willl be called as soon as the state update is resolved by setState so the new state will be available inside callAPI. this.setState({timeData}, this.callAPI); } } }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!