简体   繁体   English

如何在 React js 中立即更新状态值?

[英]How can I update state value immediately in React js?

I know setState in an async function.我知道异步函数中的setState But If I need the value of state immediately, how can I get it?但是如果我立即需要 state 的值,我怎样才能得到它呢? 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.问题是onChangeCounter值不会立即更新,它会在 2 次迭代后发生变化。 How can I solve this?我该如何解决这个问题?

setState Callback in a Class Component类组件中的 setState 回调

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获取最新和更新的状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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