提问者:小点点

检测两个条件之间的经过时间


我目前正在开发一个React应用程序,并试图检测达到某个输入值长度所需的时间。

它是一个受控输入,其值通过redux action和Reducer存储和设置。

我想在输入值为!==“”时开始计数时间,在值.length等于13时停止计数。

此外,在应用程序逻辑中,如果到达.length===13所花费的时间类似于100ms(+或-),则意味着应用程序用户使用了条形码扫描器,否则,他用键盘键入了条形码。

我尝试使用带有new Date()的var来获取时间差异,但是render()逻辑阻止了对经过时间计数的维护。。。

你知道我怎样才能达到我的目标吗?

我把组件代码留给你就在下面,提前谢谢你!

import React from "react";
import StoreInput from "../StoreInput/index";
import { connect } from "react-redux";
import "./index.scss";

import { setStoreInputFieldValue } from "../../actions/store.actions";
import { addArticleToStore } from "../../actions/articles.actions";

type ScanSetProps = {
  // Redux State
  storeInputFieldValue?: any;

  // Redux Actions
  setStoreInputFieldValue?: any;
  addArticleToStore?: any;
};

class ScanSet extends React.Component<ScanSetProps> {
  handleScanSet = (event) => {
    const { setStoreInputFieldValue } = this.props;
    setStoreInputFieldValue(event.target.value);
  };

  // Component render
  render() {
    const { storeInputFieldValue, addArticleToStore } = this.props;

    return (
      <div className="ScanSet">
        <StoreInput
          idStoreInput={"scanSetInput"}
          typeStoreInput={"number"}
          placeholderStoreInput={
            "Scannez le code barre ou saisissez le code EAN"
          }
          storeInputFillMethod={this.handleScanSet}
        />
        <button
          id="scanSetButton"
          className={
            storeInputFieldValue.length === 13
              ? "enabledButton"
              : "disabledButton"
          }
          onClick={() => addArticleToStore(storeInputFieldValue)}
        >
          Ajouter
        </button>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  storeInputFieldValue: state.store.storeInputFieldValue,
});

const mapDispatchToProps = (dispatch) => ({
  setStoreInputFieldValue: (input_value) =>
    dispatch(setStoreInputFieldValue(input_value)),
  addArticleToStore: (article_ean) => dispatch(addArticleToStore(article_ean)),
});

export default connect(mapStateToProps, mapDispatchToProps)(ScanSet);

共1个答案

匿名用户

我建议使用state。

当输入!==''时,this.setstate((state)=>{。。。state,starttime:new Date()。gettime()})当value.length===13时,this.setstate((state)=>{。。。state,endtime:new Date()。gettime()}

然后您可以有另一个部分来解释差异,(endtime-starttime)

因为您使用的是redux,如果您有一个片断说明了这一点。 您可以简单地分派这两个操作(setStartTime,setEndTime),并让reducer处理上面的逻辑。