簡體   English   中英

您如何通過單擊按鈕每秒對圖像表進行洗牌?

[英]How do you shuffle a table of images every second on the click of a button?

我有一個帶有圖像和名稱的引導表。 我的數據是一個包含圖像 URL 和名稱的對象數組。 當我單擊按鈕時,我希望圖像對象每 1 秒隨機播放一次。 我正在使用 Fisher-Yates 算法在 setInterval() 函數內部進行洗牌。

我也想知道如何創建一個停止按鈕。

模擬數據:

export const data = [{
    url: 'https://via.placeholder.com/80/FF0000',
    name: 'ben'
  },
  {
    url: 'https://via.placeholder.com/80/000000',
    name: 'jon'
  },
  {
    url: 'https://via.placeholder.com/80/FFFFFF',
    name: 'sam'
  },
  {
    url: 'https://via.placeholder.com/80/0000FF',
    name: 'bill'
  },
  {
    url: 'https://via.placeholder.com/80/008000',
    name: 'tom'
  }
];

這是我的組件:

import React, { Component } from 'react';
import { Table, Button } from 'reactstrap';
import './App.css';
import { data } from './mock-data';
import { shuffle } from './helpers/shuffle';

class App extends Component {
  constructor(props){
    super(props)
     this.state = {
      images: data
     }
   }
   handleStartShuffle = () => {
     this.setState({images: setInterval(shuffle(this.state.images), 1000)});
   }

   render () {
     const imageTable = this.state.images.map((item, index) => {
       console.log('item.url', item.url)
       return (
       <tr key={index}>
         <td>
            <img src={item.url} alt='random' />
         </td>
         <td>{item.name}</td>
       </tr>
       )
     })
     return (
       <div>
         <Table>
           <thead>
              <tr>
                <th>image</th>
                <th>name</th>
              </tr>
           </thead>
           <tbody>
              {imageTable}
           </tbody>
         </Table>
         <Button onClick={this.handleStartShuffle}>Start</Button>
       </div>
     );
   }
 }
export default App;

這是我用於改組的輔助函數:

export function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * i);
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

我會這樣做:

let interval;
handleStartShuffle = () => {
   interval = setInterval(() => {
        this.setState({images: shuffle(this.state.images)});
   }, 1000);
}
stopShuffle = () => {
   if(interval) {
       clearInterval(interval);
   }
}

@TShort 已經准確地向您展示了如何跟蹤間隔並正確停止它,所以我不會在這里復制/粘貼它。

但是,您的 shuffle 函數當前正在就地修改數組。 由於數組處於組件的狀態,這可能會導致不可預測的結果。 您需要更改函數以返回一個數組。

最簡單的解決方案是在函數的開頭復制一份:

export function shuffle(oldArray) {
  const array = [...oldArray];

setInterval 返回一個計時器 ID,然后您可以使用該 ID 調用 clearInterval。 你的例子有點模糊,特別是當你在 state.images 中存儲間隔 id 時。 請參閱在 React 組件中使用 setInterval

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM