单击提交按钮时尝试填充数组

时间:2019-05-29 07:58:58

标签: reactjs

我创建了一个带有提交按钮的计时器。此提交按钮仅填充数组的一个插槽,而不是每次单击时依次填充每个插槽。

目前,我使用提交按钮功能中的.push进行设置。这是我认为我要出错的地方。

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

const ms = require('pretty-ms');

class Timer extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      time: 0,
      start: 0,
      isOn: false, 

    }
    this.onItemMouseDown = this.onItemMouseDown.bind(this);
    this.onItemMouseUp = this.onItemMouseUp.bind(this);
    this.resetTimer = this.resetTimer.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }


  onItemMouseDown() {
    this.setState({
      time: this.state.time,
      start: Date.now() - this.state.time,
      isOn: true
    })

    //the below uses a predefined function setInterval with a nested arrow function setting the state again 
    // which is time. More detail: It compares the time to the current date and time for accuracy. The interval is 1.
    this.timer = setInterval(() => this.setState({
      time: Date.now() - this.state.start
    }), 1);


  }

  onItemMouseUp() {
    this.setState({isOn: false});
    clearInterval(this.timer);   
  }


  resetTimer() {
    this.setState({time: 0})
  }

  onSubmit() {
    const scoreArray = [];

    scoreArray.push(ms(this.state.time))

    console.log(scoreArray)

  }

  render() {

    if((this.state.isOn) === true){
    return(
      <React.Fragment>
      <div>
        <h3>timer: {ms(this.state.time)} </h3>

      </div>
    <div>
      <button onMouseDown={this.onItemMouseDown} onMouseUp={this.onItemMouseUp} >start</button>    

      <button onClick={this.resetTimer}>reset</button> 

      </div>

      </React.Fragment>
    ) 
    } else {  

      return(
        <React.Fragment>
      <div>
        <h3>Your time is: {ms(this.state.time)}</h3>
      </div>
      <div>
      <button onMouseDown={this.onItemMouseDown} onMouseUp={this.onItemMouseUp}>Start</button>  <span></span>  

      <button onClick={this.resetTimer}>Reset</button> <span></span>

      <button onClick={this.onSubmit}>Done!</button>
      </div>     
      </React.Fragment>
      )
    }
  }

}


export default Timer

  const rootElement = document.getElementById("root");
ReactDOM.render(<Timer />, rootElement);

然后,提交按钮应在每次单击时为每个阵列插槽填充一个时间值。 我倾向于考虑过多。有更好的选择吗? 我的最终目标是填充数组,然后(出于教育目的)将该数组在JSX中显示为得分/时间列表。

1 个答案:

答案 0 :(得分:2)

scoreArray数据不会保留在您的component中。按照当前的构造,每次调用onSubmit时都只是重新初始化数组。您可以将其存储为状态值。

在您的州定义中

this.state = {
  time: 0,
  start: 0,
  isOn: false, 
  scoreArray: []
}

在onSubmit()

  onSubmit() {
    const { scoreArray } = this.state;

    this.setState({
       ...this.state,
       scoreArray: [...scoreArray, (ms(this.state.time))]
    } () => console.log(this.state.scoreArray))
  }