Как можно нажать кнопку «Стоп», тасовать не может тасовать - PullRequest
0 голосов
/ 08 июля 2019

Я нажму на handleClick, он будет isplay = true и запустит «shuffle» для componentDidUpdate, и он может перемешиваться, но я нажимаю handleClick «stop», текст кнопки изменится на «shuffle», но он снова будет перемешивать данные.

Как я могу нажать «Стоп» и больше не перемешивать данные?

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