如何单击停止按钮,不能随机播放

时间:2019-07-08 16:48:07

标签: javascript reactjs settimeout shuffle cleartimeout

我将单击handleClick,它将为isplay = true并在componentDidUpdate上运行“随机播放”,并且可以随机播放,但是我单击handleClick“停止”,按钮文本将更改为“随机播放”,但是它将再次随机播放数据

我如何单击“停止”,而又不重新整理数据?

https://codesandbox.io/s/react-cardfrom-scratch-qiunp

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: DATA,
      isPlay: false,
      time: null
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(isPlay) {

    this.setState({
      isPlay: isPlay
    });
  }

  componentDidUpdate(prevProps, prevState) {
    const { isPlay } = this.state;
    if (!isPlay) {
      clearTimeout(this.time);
    } else {
      const newDATA = shuffle(DATA);
      clearTimeout(this.time);
      this.time = setTimeout(() => {
        this.setState({
          data: newDATA
        });
      }, 1000);
    }
  }

  componentWillUnmount() {
    clearTimeout(this.timer); //Clearing timeout
    this.timer = null;
  }

  renderCard() {
    const { data, isPlay } = this.state;

    return data.map(item => {
      console.log("render: ", item.title);
      return (
        <div key={item.title + item.type} className="col">
          <Card {...item} />
        </div>
      );
    });
  }

  render() {
    const { isPlay } = this.state;
    return (
      <div className="App">
        {isPlay ? (
          <Button isPlay={isPlay} onClick={() => this.handleClick(false)} />
        ) : (
          <Button isPlay={isPlay} onClick={() => this.handleClick(true)} />
        )}
        <div className="container clearfix">{this.renderCard()}</div>
      </div>
    );
  }
}

0 个答案:

没有答案