为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信