亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React:如何強制 setState()?

React:如何強制 setState()?

慕婉清6462132 2023-03-18 17:01:01
在這個 React 中,Javascript 計算器 this.setState({ array: displayed});應該更新狀態中的數組,但它沒有。有沒有辦法強迫它?任何幫助將不勝感激。索引.jsimport React from 'react';import ReactDOM from 'react-dom';import './style.css';class JavascriptCalculator extends React.Component {  constructor(props) {    super(props);    this.state = {      text: 0,      array: [],      operators:['+']    }    this.display = this.display.bind(this);    this.clear = this.clear.bind(this);    this.calculate = this.calculate.bind(this);  }  display(text){    // if display is zero, remove the leading zero from the text.    if(this.state.text == 0){      this.state.text = ''    }    let regex = /[*/+-]/;    // if text is not an operator    if (!regex.test(text)){      let displayed = this.state.text      // disallow consecutive decimal points      if (text == '.' && displayed.slice(-1) == '.'){        return;      }      // start by adding text      displayed = this.state.text += text;      // disallow multiple decimal points in a number      // if attempt at more than one decimal point remove last one.      let array = displayed.split('');      let count = 0;      for (let i = 0; i < array.length; i++){        if (array[i] == '.'){          count++;        }      }      // one decimal point is allowed per operator.      // thus to allow the first decimal point,      // this.state.operators must be initialized      // to length of 1.      if(count > this.state.operators.length){        array.pop();      }      displayed = array.join('');      this.setState({ text: displayed});    }
查看完整描述

1 回答

?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

setState 是異步的。它不會按照你的使用方式工作。在您的情況下,您應該只將displayed數組傳遞給計算函數。



查看完整回答
反對 回復 2023-03-18
  • 1 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號