簡體   English   中英

如何在 React js 中立即更新狀態值?

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

我知道異步函數中的setState 但是如果我立即需要 state 的值,我怎樣才能得到它呢? 這是我的代碼

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});
          };

問題是onChangeCounter值不會立即更新,它會在 2 次迭代后發生變化。 我該如何解決這個問題?

類組件中的 setState 回調

那就是狀態值更新后會執行的回調函數。 並且您可以調用任何其他函數來獲取最新的狀態更新。

即:

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