繁体   English   中英

我将如何显示对象数组中的随机字符串。 在时间循环上。 [反应]

[英]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>
  );
};

编辑confidence-herschel-21og0

您可以使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM