[英]How would I display a random string from an array of objects. On a a time loop. [React]
I'm attempting to make a simple app displaying a random quote.我正在尝试制作一个显示随机报价的简单应用程序。 With a time interval.
有时间间隔。 Though I'm struggling to understand how I could randomise a quote on a timer and display the content.
虽然我很难理解如何在计时器上随机引用并显示内容。
My code so far:到目前为止我的代码:
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>
);
}
currently I'm using hard coded data which looks like this:目前我正在使用看起来像这样的硬编码数据:
const data = [
{id: 1, author: 'suzy', quote: 'hello world'}
]
I would like to learn how to display a random quote with the authors name, then after a couple of seconds display a different one.我想学习如何显示作者姓名的随机引用,然后在几秒钟后显示不同的引用。 Also not display the same quote twice in one session if possible.
如果可能,也不要在一个会话中两次显示相同的报价。
Compute a random index Math.floor(Math.random() * data.length)
计算随机索引
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);
RandomQuote随机报价
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>
);
};
You can use setTimeout nested or setInterval, and the you can use a observer to keep track of previously used id's and once it goes over the session we can reset the timer and observer您可以使用 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)
First you should import data as full arry of obj then create random function like首先,您应该将数据作为 obj 的完整 arry 导入,然后创建随机函数,例如
const rand = function () {
return Math.floor(Math.random() * data.length)
} }
and use it并使用它
< h1 className = 'quote' > { data[rand()].quote }</h1 >
also you can use你也可以使用
< span className = 'author' > - { data[rand()].author }</span >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.