[英]How would I display a random string from an array of objects. On a a time loop. [React]
我正在嘗試制作一個顯示隨機報價的簡單應用程序。 有時間間隔。 雖然我很難理解如何在計時器上隨機引用並顯示內容。
到目前為止我的代碼:
import { useState } from 'react';
import { data } from './hardCode';
export default function Index() {
const [quotes, setQuotes] = useState(data);
console.log(quotes);
return (
<main>
<div className='wrapper'>
<div className='feature'>
<div className='quote-wrapper'>
<h1 className='quote'>"{quotes[0].quote}"</h1>
</div>
<div className='author-wrapper'>
<span className='author'>- {quotes[0].author}</span>
</div>
</div>
</div>
</main>
);
}
目前我正在使用看起來像這樣的硬編碼數據:
const data = [
{id: 1, author: 'suzy', quote: 'hello world'}
]
我想學習如何顯示作者姓名的隨機引用,然后在幾秒鍾后顯示不同的引用。 如果可能,也不要在一個會話中兩次顯示相同的報價。
計算隨機索引Math.floor(Math.random() * data.length)
const data = [ {id: 1, author: 'suzy', quote: 'hello world'}, {id: 4, author: 'bob', quote: 'hello world 2'}, {id: 3, author: 'carrie', quote: 'hello world 3'}, {id: 5, author: 'timmy', quote: 'hello world 4'}, {id: 2, author: 'bob', quote: 'hello world 5'}, ]; const randIndex = Math.floor(Math.random() * data.length); console.log(data[randIndex].quote);
隨機報價
const getRandIndex = arr => Math.floor(Math.random() * arr.length);
const RandomQuote = ({ data, interval = 2000 }) => {
const [quotes, setQuotes] = useState(data);
const [currentQuote, setCurrentQuote] = useState();
/**
* Select a quote at random and remove from the current list of
* selectable quotes, reducing the array length by 1
*/
const getRandomQuote = useCallback(() => {
const randIndex = getRandIndex(quotes);
setCurrentQuote(quotes[randIndex]);
setQuotes(quotes => quotes.filter((_, i) => i !== randIndex));
}, [quotes]);
// Get initial random quote and setup interval and cleanup function
useEffect(() => {
!currentQuote && getRandomQuote();
const timer = quotes.length && setInterval(getRandomQuote, interval);
return () => clearInterval(timer);
}, [currentQuote, getRandomQuote, interval, quotes]);
return (
<main>
<div className="wrapper">
<div className="feature">
{currentQuote && (
<Fragment>
<div className="quote-wrapper">
<h1 className="quote">"{currentQuote.quote}"</h1>
</div>
<div className="author-wrapper">
<span className="author">- {currentQuote.author}</span>
</div>
</Fragment>
)}
</div>
</div>
</main>
);
};
您可以使用 setTimeout 嵌套或 setInterval,並且您可以使用觀察者來跟蹤以前使用的 id,一旦它結束會話,我們就可以重置計時器和觀察者
const data = [ {id: 1, author: 'suzy', quote: 'hello world'}, {id: 4, author: 'bob', quote: 'hello world 2'}, {id: 3, author: 'carrie', quote: 'hello world 3'}, {id: 5, author: 'timmy', quote: 'hello world 4'}, {id: 2, author: 'bob', quote: 'hello world 5'}, ]; function observerReset(){ if(Date.now() - timer >= 2000 * data.length && Object.keys(observer).length === data.length){ console.log('observer reset') observer = {} timer = Date.now() } } function randomIndex(){ let randIndex = undefined while(observer[randIndex] === undefined){ randIndex = Math.floor( Math.random() * data.length); if(observer[randIndex] === undefined ){ observer[randIndex] = randIndex } else { randIndex = undefined } } return randIndex } let observer = {} let timer = Date.now() setTimeout(function quotePrinter() { observerReset() let randIndex = randomIndex(); let { author, quote } = data[randIndex] console.log(`${author}: ${quote}`); setTimeout(quotePrinter, 2000) }, 2000)
首先,您應該將數據作為 obj 的完整 arry 導入,然后創建隨機函數,例如
const rand = function () {
return Math.floor(Math.random() * data.length)
}
並使用它
< h1 className = 'quote' > { data[rand()].quote }</h1 >
你也可以使用
< span className = 'author' > - { data[rand()].author }</span >
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.