React:如何强制 setState()?

在这个 React 中,Javascript 计算器 this.setState({ array: displayed});应该更新状态中的数组,但它没有。有没有办法强迫它?任何帮助将不胜感激。


索引.js


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

    }

慕婉清6462132
浏览 125回答 1
1回答

慕码人8056858

setState 是异步的。它不会按照你的使用方式工作。在您的情况下,您应该只将displayed数组传递给计算函数。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript