简体   繁体   中英

How can I update state value immediately in React js?

I know setState in an async function. But If I need the value of state immediately, how can I get it? This is my code

class OfficerPage extends Component {
    constructor(props) {
        super(props);
    
        this.state={
            counterList: [],
            currentCustomerValue: null,
            counterValue: null
        }
      }

      componentDidMount(){
        this.getAllCounters();
        this.getCurrentTicketId(this.state.counterValue) //cannot get value immidately
      }

      getAllCounters=()=>{
          API.getAllCounters().then((res) => {
            let allCounters=[];
            for(let i=0; i<res.length; i++){
              allCounters.push(res[i]);
            }
            this.setState({counterList: allCounters} )
         })
         .catch((err) => {
          this.setState({AuthErr : err.msg});
         });
        }


        getCurrentTicketId=(counterValue)=>{
            API.getCurrentTicketId(counterValue).then((res) => {
              this.setState({currentCustomerValue: res})
           })
           .catch((err) => {
            this.setState({AuthErr : err.msg});
           });
          }

          onChangeCounter = (event) => {
            console.log(event.target.value+" vall");
            this.setState({counterValue: event.target.value});
          };

Problem is onChangeCounter value does not update immediately, it changes after 2 iterations. How can I solve this?

setState Callback in a Class Component

That's the callback function that will be executed after the state value is updated. and you can call any other functions to get the latest state updates.

For namely:

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      age: 0,
    };
  }
  
  // this.checkAge is passed as the callback to setState
  updateAge = (value) => {
    this.setState({ age: value}, this.checkAge);
// When the Age state has updated, this.checkAge will be executed without depending on the React render method.
  };

  checkAge = () => {
    const { age } = this.state;
    if (age !== 0 && age >= 21) {
      // Make API call to /beer
    } else {
      // Throw error 404, beer not found
    }
  };

  render() {
    const { age } = this.state;
    return (
      <div>
        <p>Drinking Age Checker</p>
        <input
          type="number"
          value={age}
          onChange={e => this.updateAge(e.target.value)}
        />
      </div>
    );
  }

}

export default App;

如果您不熟悉setState回调函数,也可以使用componentDidUpdate获取最新和更新的状态。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM