为数组中的每个项目创建独立的秒表。根据API返回的数据设置停止时间

Umb*_*bro 7 javascript ecmascript-6 reactjs

创建独立的秒表。我有两个名为A和的元素B。当我单击该A元素时,Hello将显示其描述和秒表。当我单击该B元素时,World将显示其描述和秒表。我的秒表有问题。当我单击该元素A并启动秒表时,请转到该元​​素,B然后此秒表将运行。我的目标是,当我为该元素运行秒表时,A它将仅计入该元素。当他将秒表停在元素A中并转到元素时B,秒表将仅在该元素中计数。我将秒表停在B元素中,然后转到A元素,我将能够恢复秒表。我正在寻求一些想法来解决这个问题。我通过调用startTime函数(方法发布->具有开始日期的对象)进行发送。我单击停止->调用stopTimer(方法发布->我向对象发送结束日期)。作为响应,该项目将带有开始日期和结束日期,并且将秒数(结束日期与开始日期之间的差)保存在状态中。根据这些数据(开始日期,结束日期和秒),设置秒表停止的时间。如何关闭浏览器以下载此数据以设置其停止时间。请给我一些提示。我将定期更正我的代码,并将其插入此处。

预期效果:

单击元素A->开始秒表->秒表停止->单击元素B->开始秒表->返回元素A->恢复计时器停止时间

整个代码在这里:https : //stackblitz.com/edit/react-x9h42z

部分代码:

App.js

class App extends React.Component {
  constructor() {
    super();

    this.state = {

      items: [
        {
          name: 'A',
          description: 'Hello'
        },
        {
          name: 'B',
          description: 'World'
        }
      ],
      selectIndex: null
    };
  }

  select = (index) => {
    this.setState({
      selectIndex: index
    })
  }


  render() {
    console.log(this.state.selectIndex)
    return (
      <div>
        <ul>
          {
            this.state.items
              .map((item, index) =>
                <Item
                  key={index}
                  index={index}
                  item={item}
                  select={this.select}
                  items = {this.state.items}
                  selectIndex = {this.state.selectIndex}
                />
              )
          }
        </ul>
         <ItemDetails
            items = {this.state.items}
            selectIndex = {this.state.selectIndex}

        />
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

跑表

class Stopwatch extends Component {
  constructor() {
    super();

    this.state = {
      timerOn: false,
      timerStart: 0,
      timerTime: 0
    };
  }

  startTimer = () => {
    this.setState({
      timerOn: true,
      timerTime: this.state.timerTime,
      timerStart: Date.now() - this.state.timerTime
    });
    this.timer = setInterval(() => {
      this.setState({
        timerTime: Date.now() - this.state.timerStart
      });
    }, 10);
  };

  stopTimer = () => {
    this.setState({ timerOn: false });
    clearInterval(this.timer);
  };

  resetTimer = () => {
    this.setState({
      timerStart: 0,
      timerTime: 0
    });
  };

  render() {
      const { timerTime } = this.state;
      let centiseconds = ("0" + (Math.floor(timerTime / 10) % 100)).slice(-2);
      let seconds = ("0" + (Math.floor(timerTime / 1000) % 60)).slice(-2);
      let minutes = ("0" + (Math.floor(timerTime / 60000) % 60)).slice(-2);
      let hours = ("0" + Math.floor(timerTime / 3600000)).slice(-2);

    return (
      <div>


    <div className="Stopwatch-display">
      {hours} : {minutes} : {seconds} : {centiseconds}
    </div>


    {this.state.timerOn === false && this.state.timerTime === 0 && (
    <button onClick={this.startTimer}>Start</button>
    )}

    {this.state.timerOn === true && (
      <button onClick={this.stopTimer}>Stop</button>
    )}

    {this.state.timerOn === false && this.state.timerTime > 0 && (
      <button onClick={this.startTimer}>Resume</button>
    )}

    {this.state.timerOn === false && this.state.timerTime > 0 && (
      <button onClick={this.resetTimer}>Reset</button>
    )}
        </div>
      );
    }
}
Run Code Online (Sandbox Code Playgroud)

Bha*_*t23 5

您需要为每个列表项创建两个秒表实例。我已经修改了链接链接你提供。我在您的列表数组中向每个对象添加了秒表,并对每个对象添加了唯一键,以使React知道它们是不同的组件。现在,我只是用秒表呈现所有列表项,并且即使在切换后也要维护每个秒表的状态,我只是使用一种简单的显示无技术,而不是完全删除该组件。检查代码,让我知道它是否适合您?

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';


class Item extends Component {

  render() {
    const selectItem = this.props.items[this.props.selectIndex]
    console.log(selectItem);
    
    return ( 
      
        <li onClick={() => this.props.select(this.props.index)}>
          <div>
            Name:{this.props.item.name}
          </div>
        </li>
    )
  }
}

class ItemDetails extends Component {
 
  render() {
    const selectItem = this.props.items[this.props.selectIndex]
    console.log(selectItem);
    let content = this.props.items.map((item, index) => {
      return (
        <div className={this.props.selectIndex === index?'show':'hide'}>
          <p>
              Description:{item.description}
          </p>
          {item.stopWatch}
        </div>
      );
    })
    return (  
      <div>
        {selectItem ?
            content
          :
          null
        }
      </div>
    )
  }
}

class App extends React.Component {
  constructor() {
    super();

    this.state = {

      items: [
        {
          name: 'A',
          description: 'Hello',
          stopWatch: <Stopwatch key={1} />
        },
        {
          name: 'B',
          description: 'World',
          stopWatch: <Stopwatch key={2} />
        }
      ],
      selectIndex: null
    };
  }

  select = (index) => {
    this.setState({
      selectIndex: index
    })
  }


  render() {
    console.log(this.state.selectIndex)
    return (
      <div>
        <ul>
          {
            this.state.items
              .map((item, index) =>
                <Item
                  key={index}
                  index={index}
                  item={item}
                  select={this.select}
                  items = {this.state.items}
                  selectIndex = {this.state.selectIndex}
                />
              )
          }
        </ul>
         <ItemDetails
            items = {this.state.items}
            selectIndex = {this.state.selectIndex}

        />
      </div>
    );
  }
}


class Stopwatch extends Component {
  constructor() {
    super();

    this.state = {
      timerOn: false,
      timerStart: 0,
      timerTime: 0
    };
  }

  startTimer = () => {
    this.setState({
      timerOn: true,
      timerTime: this.state.timerTime,
      timerStart: Date.now() - this.state.timerTime
    });
    this.timer = setInterval(() => {
      this.setState({
        timerTime: Date.now() - this.state.timerStart
      });
    }, 10);
  };

  stopTimer = () => {
    this.setState({ timerOn: false });
    clearInterval(this.timer);
  };

  resetTimer = () => {
    this.setState({
      timerStart: 0,
      timerTime: 0
    });
  };

  render() {
      const { timerTime } = this.state;
      let centiseconds = ("0" + (Math.floor(timerTime / 10) % 100)).slice(-2);
      let seconds = ("0" + (Math.floor(timerTime / 1000) % 60)).slice(-2);
      let minutes = ("0" + (Math.floor(timerTime / 60000) % 60)).slice(-2);
      let hours = ("0" + Math.floor(timerTime / 3600000)).slice(-2);

    return (
      <div>
      

    <div className="Stopwatch-display">
      {hours} : {minutes} : {seconds} : {centiseconds}
    </div>


    {this.state.timerOn === false && this.state.timerTime === 0 && (
    <button onClick={this.startTimer}>Start</button>
    )}

    {this.state.timerOn === true && (
      <button onClick={this.stopTimer}>Stop</button>
    )}

    {this.state.timerOn === false && this.state.timerTime > 0 && (
      <button onClick={this.startTimer}>Resume</button>
    )}
    
    {this.state.timerOn === false && this.state.timerTime > 0 && (
      <button onClick={this.resetTimer}>Reset</button>
    )}
        </div>
      );
    }
}


render(<App />, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)
h1, p {
  font-family: Lato;
}

.show {
  display: block;
}

.hide {
  display: none;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Run Code Online (Sandbox Code Playgroud)


Mun*_*nna 3

您的秒表不会更新,因为您的渲染方法始终返回<Stopwatch />,因此即使selectItem更改反应不会<Stopwatch />为您渲染新组件,它也会显示旧组件。

return (
  <div>
    {selectItem ?
      <div>
        <p>Description:{selectItem.description}</p>
        <Stopwatch />
      </div>
      :
      null
    }
  </div>
)
Run Code Online (Sandbox Code Playgroud)

为了让 React 为您渲染一个新组件,您需要将一个key属性传递给您的组件。

return (
  <div>
    {selectItem ?
      <div>
        <p>Description:{selectItem.description}</p>
        <Stopwatch key={selectItem.name}/>
      </div>
      :
      null
    }
  </div>
)
Run Code Online (Sandbox Code Playgroud)

现在,当您在秒表之间切换时,React 会为您渲染新组件,但每次您执行此操作时,秒表都会重置,因为组件本身会重新渲染并初始化您的状态变量。

这就是状态管理的用武之地。您可以使用 REDUX 来管理组件状态。如果您希望秒表在后台运行,您还可以编写一个简单的服务来为您完成此操作。

演示: stackblitz