显示并在Next.js中对数组进行洗牌。

huangapple go评论80阅读模式
英文:

Display and shuffle an array in Next.js

问题

I can see that you want to create a single "Card" component that displays content from a data.js file, with the content changing randomly on every refresh. To achieve this, you can modify your page.js as follows:

import React, { useEffect, useState } from 'react';
import Card from './components/Card';
import { curses } from '@/utils/curses';

export default function Home() {
  const [data, setData] = useState([]);
  const [randomIndex, setRandomIndex] = useState(0);

  useEffect(() => {
    const loadCurse = curses;
    setData(loadCurse);
    setRandomIndex(getRandomIndex(data.length));
  }, []);

  const getRandomIndex = (max) => {
    return Math.floor(Math.random() * max);
  };

  return (
    <main className="flex items-center justify-center h-screen">
      <div>
        {data.slice(randomIndex, randomIndex + 1).map((item, id) => {
          return (
            <Card
              key={id}
              curse={item.curse}
              russo={item.russo}
              trad={item.trad}
            />
          );
        })}
      </div>
    </main>
  );
}

This code sets up a randomIndex state that holds a random index from your data array. When the component loads, it initializes this index, and the Card component displays the corresponding data element. With this code, the content displayed in the card will change on every refresh.

英文:

I'd like to create a single "Card" component containing some content like title, subtitle, etc picked from a data.js file which contains an array with all these elements. What I want to achive is, it must changes on every refresh giving a different result from the array picked randomly.

For the moment, I could display the single Card element using .map and .slice, but as I said, I'd like to make it changes on every refresh.

Card.js:

import React from &quot;react&quot;;
import { curses } from &quot;@/utils/curses&quot;;

function Card({ id, curse, russo, trad }) {
  return (
    &lt;div className=&quot;flex text-center items-center h-[300px]	p-3 bg-card&quot;&gt;
      &lt;div className=&quot;h-[280px] border-2 border-black p-4&quot;&gt;
        &lt;h1 className=&quot;font-bold p-4 text-4xl&quot;&gt;{curse}&lt;/h1&gt;
        &lt;p&gt;Russian: {russo} &lt;/p&gt;
        &lt;p&gt;Meaning: {trad} &lt;/p&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
}

export default Card;

page.js:

&quot;use client&quot;;

import Card from &quot;./components/Card&quot;;

import { useEffect, useState } from &quot;react&quot;;
import { curses } from &quot;@/utils/curses&quot;;

const inter = Inter({ subsets: [&quot;latin&quot;] });

export default function Home() {
  const [data, setData] = useState([]);

  useEffect(() =&gt; {
    const loadCurse = curses;
    setData(loadCurse);
  }, []);

  return (
    &lt;main className=&quot;flex items-center justify-center h-screen&quot;&gt;
      &lt;div&gt;
        {data.slice(0, 1).map((item, id) =&gt; {
          return (
            &lt;Card
              key={id}
              curse={item.curse}
              russo={item.russo}
              trad={item.trad}
            /&gt;
          );
        })}
      &lt;/div&gt;
    &lt;/main&gt;
  );
}

data.js:

export const curses = [
  {
    id: &quot;1&quot;,
    curse: &quot;Curse 1&quot;,
    russo: &quot;&quot;,
    trad: &quot;&quot;,
  },
  {
    id: &quot;2&quot;,
    curse: &quot;Curse 2&quot;,
    russo: &quot;XYZ&quot;,
    trad: &quot;&quot;,
  },
  {
    id: &quot;3&quot;,
    curse: &quot;Curse 3&quot;,
    russo: &quot;AAA&quot;,
    trad: &quot;&quot;,
  },
  {
    id: &quot;4&quot;,
    curse: &quot;Curse 4&quot;,
    russo: &quot;&quot;,
    trad: &quot;&quot;,
  },
  {
    id: &quot;5&quot;,
    curse: &quot;Curse 6&quot;,
    russo: &quot;&quot;,
    trad: &quot;&quot;,
  },
  {
    id: &quot;6&quot;,
    curse: &quot;Curse 7&quot;,
    russo: &quot;&quot;,
    trad: &quot;&quot;,
  },
  {
    id: &quot;7&quot;,
    curse: &quot;Curse 8&quot;,
    russo: &quot;&quot;,
    trad: &quot;&quot;,
  },
  {
    id: &quot;8&quot;,
    curse: &quot;Curse 9&quot;,
    russo: &quot;&quot;,
    trad: &quot;&quot;,
  },
  {
    id: &quot;9&quot;,
    curse: &quot;Curse 10&quot;,
    russo: &quot;&quot;,
    trad: &quot;&quot;,
  },
];

How can I achieve this?

答案1

得分: 0

我认为你可以使用JavaScript的Math.random()函数来实现这个功能。

import { useEffect, useState } from "react";
import { curses } from "@/utils/curses";

const inter = Inter({ subsets: ["latin"] });

export default function Home() {
  const [data, setData] = useState([]);
  const [index, setIndex] = useState(0);

  useEffect(() => {
    const loadCurse = curses;
    const randomIndex = parseInt(loadCurse.length * Math.random());
    setData(loadCurse);
    setIndex(randomIndex)
  }, []);

  return (
    <main className="flex items-center justify-center h-screen">
      <div>
        {data.length > 0 && <Card
          curse={data[index].curse}
          russo={data[index].russo}
          trad={data[index].trad}
        />}
      </div>
    </main>
  );
}
英文:

I think you can implement this with Math.random() function of javascript

import { useEffect, useState } from &quot;react&quot;;
import { curses } from &quot;@/utils/curses&quot;;

    const inter = Inter({ subsets: [&quot;latin&quot;] });
    
    export default function Home() {
      const [data, setData] = useState([]);
      const [index, setIndex] = useState(0);
    
      useEffect(() =&gt; {
        const loadCurse = curses;
        const randomIndex = parseInt(loadCurse.length * Math.random());
        setData(loadCurse);
        setIndex(randomIndex)
      }, []);
    
      return (
        &lt;main className=&quot;flex items-center justify-center h-screen&quot;&gt;
          &lt;div&gt;
              {data.length &gt; 0 &amp;&amp; &lt;Card
                  curse={data[index].curse}
                  russo={data[index].russo}
                  trad={data[index].trad}
                /&gt;}
          &lt;/div&gt;
        &lt;/main&gt;
      );

}

答案2

得分: 0

以下是您提供的代码的翻译部分:

我会这样做

    import Card from "./components/Card";
    
    import { useEffect, useState } from "react";
    import { curses } from "@/utils/curses";
    
    const inter = Inter({ subsets: ["latin"] });
    
    export default function Home() {
      const [data, setData] = useState();
    
      useEffect(() => {
        setData(curses[Math.floor(Math.random() * curses.length)]);
      }, []);
    
      return (
        <main className="flex items-center justify-center h-screen">
          <div>
            {data && (
                <Card
                  key={data.id}
                  curse={data.curse}
                  russo={data.russo}
                  trad={data.trad}
                />
            )}
          </div>
        </main>
      );
    }

**注意**如果您想在不刷新浏览器页面的情况下在任何事件下生成另一张卡片可以将代码放入该事件中

如果您想添加一个按钮来更改内容

    import Card from "./components/Card";
    
    import { useEffect, useState } from "react";
    import { curses } from "@/utils/curses";
    
    const inter = Inter({ subsets: ["latin"] });
    
    export default function Home() {
      const [data, setData] = useState();

      const generate = () => {
         setData(curses[Math.floor(Math.random() * curses.length)]);
      }
    
      useEffect(() => {
        generate();
      }, []);
    
      return (
        <main className="flex items-center justify-center h-screen">
          <div>
            {data && (
                <Card
                  key={data.id}
                  curse={data.curse}
                  russo={data.russo}
                  trad={data.trad}
                />
            )}
        <button type="button" onClick={() => generate()}>Another</button>
          </div>
        </main>
      );
    }
英文:

I would do this:

import Card from &quot;./components/Card&quot;;
import { useEffect, useState } from &quot;react&quot;;
import { curses } from &quot;@/utils/curses&quot;;
const inter = Inter({ subsets: [&quot;latin&quot;] });
export default function Home() {
const [data, setData] = useState();
useEffect(() =&gt; {
setData(curses[Math.floor(Math.random() * curses.length)]);
}, []);
return (
&lt;main className=&quot;flex items-center justify-center h-screen&quot;&gt;
&lt;div&gt;
{data &amp;&amp; (
&lt;Card
key={data.id}
curse={data.curse}
russo={data.russo}
trad={data.trad}
/&gt;
)}
&lt;/div&gt;
&lt;/main&gt;
);
}

EDIT keep in mind if you want to generate another card under any event without refreshing your browser page you can place the code in the effect into that event.

In case you want to add a button to make the content change:

import Card from &quot;./components/Card&quot;;
import { useEffect, useState } from &quot;react&quot;;
import { curses } from &quot;@/utils/curses&quot;;
const inter = Inter({ subsets: [&quot;latin&quot;] });
export default function Home() {
const [data, setData] = useState();
const generate = () =&gt; {
setData(curses[Math.floor(Math.random() * curses.length)]);
}
useEffect(() =&gt; {
generate();
}, []);
return (
&lt;main className=&quot;flex items-center justify-center h-screen&quot;&gt;
&lt;div&gt;
{data &amp;&amp; (
&lt;Card
key={data.id}
curse={data.curse}
russo={data.russo}
trad={data.trad}
/&gt;
)}
&lt;button type=&quot;button&quot; onClick={() =&gt; generate()}&gt;Another&lt;/button&gt;
&lt;/div&gt;
&lt;/main&gt;
);
}

huangapple
  • 本文由 发表于 2023年2月18日 19:33:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75493037.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定