我有一个报价生成器,我正试图实现一个功能,显示在特定数量的对象在时间.我试过使用map,但它返回它不是一个函数.现在我有它来生成一个随机引用,但我想有一个选项,以显示一个特定的数字.如有任何帮助,我们不胜感激.这就是起作用的方法,但我注释掉了,以试用这张 map .

App.js

import { useState, useEffect } from "react";
import Footer from "./Components/Footer/Footer";
import Quote from "./Components/Quote/Quote";
import "./App.css"
import { data } from "./Components/Data/Data";
import { characterData } from "./Components/Data/CharacterData"
import CharacterBios from "./Components/CharacterBios/CharacterBios";
import Header from "./Components/Header/Header";

function App() {
  const [quote, setQuote] = useState();
  const [isLoading, setIsLoading] = useState(true);
  const randomise = () => {
    const randomNumber = Math.floor(Math.random() * data.length);
    setQuote(data[randomNumber]);
  };
  //math.floor makes it a whole number, and the equation above goes through the data at random
  useEffect(() => {
    randomise();
    setIsLoading(false);
  }, []);

  return (
    <div className="App">
      <Header />
      <div className="main">

      <h1>Quote Generator</h1>
      {isLoading ? <p>Quote now loading...</p> : <Quote data={quote} />}
      <button onClick={randomise}>Generate Quote</button>
      <CharacterBios characterData={characterData} />
      <Footer />
      </div>
    </div>
  );
}

export default App;

Jsx:Quote.jsx

import React from 'react'


const Quote = ({data}) => {

    return (
        <div className='container quote-section'>

<div className="row">

{data.slice(0).map((item,index)=> (

    <div className="col-xl-4 col-lg-4 col-md-6 col-sm-12" key={index}> 
       
        <div className="marked-content-card">

            <p><span className="name">{item.name}</span></p>
            <p>{item.quote}</p>
        </div>
    </div>

))}



</div>

            {/* <blockquote> {
                data.quote
            }
                <p>-{
                    data.name
                }</p>
            </blockquote> */}



        </div>

    )
}

export default Quote;

推荐答案

以下是您可以做的:

  1. 使用数组表示引用状态
  2. Randomize by:
    • 克隆报价数组->;tempData = [...data]
    • 创建一个数组来保存要设置的报价->;tempQuotes
    • Iterate for the number of quotes you need and:
      • 在使用Randome索引的tempQuotes个引用中,splice()个引用
      • push加成tempQuotes
        • 扩散...,因为splice返回数组
      • 使用tempData中的其余引号再次迭代
  3. 设置新的报价状态
  4. 贴图和渲染

Code Sandbox

import { useState, useEffect } from "react";

const data = [
  "Another one bites the dust",
  "Sweet dreams are made of this",
  "Never gonna give you up",
  "Highway to the danger zone",
  "Let the bodies hit the floor",
  "Hey now, I'm an allstar",
  "Hello darkness my old friend"
];

function App() {
  const [quotes, setQuotes] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const numberOfQuotes = 3;

  const randomise = () => {
    const tempData = [...data];
    const tempQuotes = [];
    for (let i = 0; i < numberOfQuotes; i++) {
      const randomNumber = Math.floor(Math.random() * tempData.length);
      tempQuotes.push(...tempData.splice(randomNumber, 1));
    }
    setQuotes(tempQuotes);
  };
  
  useEffect(() => {
    randomise();
    setIsLoading(false);
  }, []);

  const quoteEls = quotes.map((quote) => <li class="quote">{quote}</li>);

  return (
    <div className="App">
      <div className="main">
        <h1>Quote Generator</h1>
        {isLoading ? <p>Quote now loading...</p> : quoteEls}
        <button onClick={randomise}>Generate Quote</button>
      </div>
    </div>
  );
}

export default App;

如果data很大,并且您不想每次都将其克隆到内存中,则可以:

  1. 使用Array.from()创建一个索引数组,即[0,1,2,3]
  2. 随机抽取splice个指数,就像我们上面做的那样
  3. 将该数组map存储到您的数据

下面的函数只是为了演示,但如果决定这样做,它将很容易集成到您的代码中.

const data = [
  "Another one bites the dust",
  "Sweet dreams are made of this",
  "Never gonna give you up",
  "Highway to the danger zone",
  "Let the bodies hit the floor",
  "Hey now, I'm an allstar",
  "Hello darkness my old friend"
];

const numberOfQuotes = 3

function randomize() {
  const quoteIndices = []
  const indices = Array.from({length: data.length}, (a,i) => i) // Make array of indices
  for (let i = 0; i < numberOfQuotes; i++){
    let randomNumber = Math.floor(Math.random() * indices.length);
    quoteIndices.push(...indices.splice(randomNumber, 1))
  }
  return quoteIndices.map(index => data[index])
}

console.log(randomize())

Javascript相关问答推荐

如何为GrapesJS模板编辑器创建自定义撤销/重复按钮?

我在这个黑暗模式按钮上做错了什么?

react/redux中的formData在expressjs中返回未定义的req.params.id

格式值未保存在redux持久切片中

如何从JSON数组添加Google Maps标记—或者如何为数组添加参数到标记构造器

防止用户在selectizeInput中取消 Select 选项

网页自检测外部元素无法加载

Chromium会将URL与JS一起传递到V8吗?

无法从NextJS组件传递函数作为参数'

使用JQuery单击元素从新弹出窗口获取值

保持物品顺序的可变大小物品分配到平衡组的算法

正则表达式,允许我匹配除已定义的子字符串之外的所有内容

为什么当我更新数据库时,我的所有组件都重新呈现?

是否可以将异步调用与useState(UnctionName)一起使用

用于测试其方法和构造函数的导出/导入类

我的NavLink活动类在REACT-ROUTER-V6中出现问题

是否有静态版本的`instanceof`?

将Windows XP转换为原始数据以在html前端中显示

Rails 7:在不使用导入映射的情况下导入Java脚本

当一条路由在Reaction路由中命中时,如何有条件地渲染两个组件或更改两个插座?