获取数组的前几个元素,然后获取接下来的几个元素如何做?

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

How to get the first elements of an array and then get the next few elements?

问题

这是你提供的代码的翻译部分:

I'm building my blog page for my website and I have a posts folder with markdown files of my blogs. I'm just figuring out a way to display all the blogs on a page, but I want to optimize it a bit so it doesn't try to load all blog posts at once but only the first 6, for example. And then when you click on a Load More button, the next 6 get loaded and displayed.

This is the code I'm using to get the data from my blog posts:

async function getBlogPosts(n: number) {
  const files = fs.readdirSync('posts');

  const posts = files.slice(0, n).map((fileName) => {
    const slug = fileName.replace('.md', '');
    const readFile = fs.readFileSync(`posts/${fileName}`, 'utf-8');
    const { data: frontmatter } = matter(readFile);
    return {
      slug,
      frontmatter,
    };
  });

  return posts;
}

And then display the title of the posts:

export default async function Blogs() {
  const posts = await getBlogPosts(6);

  return (
    <div className="mx-auto flex">
      {posts.map(({ slug, frontmatter }) => (
        <div
          key={slug}
          className="m-2 flex flex-col overflow-hidden rounded-xl border border-gray-200 shadow-lg"
        >
          <Link href={`/blog/${slug}`}>
            <h3 className="p-4">{frontmatter.title}</h3>
          </Link>
        </div>
      ))}
    </div>
  );
}

How would one go about implementing this?

Because I think if I were to call getBlogPosts(12), it would load 12 posts but also the first 6 which have already been loaded.

英文:

I'm building my blog page for my website and I have a posts folder with markdown files of my blogs. I'm just figuring out a way to display all the blogs on a page, but I want to optimize it a bit so it doesn't try to load all blog posts at once but only the first 6 for example. And then when you click on a Load More button the next 6 get loaded and displayed.

This is the code I'm using to get the data from my blog posts:

async function getBlogPosts(n: number) {
  const files = fs.readdirSync(&#39;posts&#39;);

  const posts = files.slice(0, n).map((fileName) =&gt; {
    const slug = fileName.replace(&#39;.md&#39;, &#39;&#39;);
    const readFile = fs.readFileSync(`posts/${fileName}`, &#39;utf-8&#39;);
    const { data: frontmatter } = matter(readFile);
    return {
      slug,
      frontmatter,
    };
  });

  return posts;
}

And then display the title of the posts:

export default async function Blogs() {
  const posts = await getBlogPosts(6);

  return (
    &lt;div className=&quot;mx-auto flex&quot;&gt;
      {posts.map(({ slug, frontmatter }) =&gt; (
        &lt;div
          key={slug}
          className=&quot;m-2 flex flex-col overflow-hidden rounded-xl border border-gray-200 shadow-lg&quot;
        &gt;
          &lt;Link href={`/blog/${slug}`}&gt;
            &lt;h3 className=&quot;p-4&quot;&gt;{frontmatter.title}&lt;/h3&gt;
          &lt;/Link&gt;
        &lt;/div&gt;
      ))}
    &lt;/div&gt;
  );
}

How would one go about implementing this?

Because I think if I were to call GetBlogPosts(12) it would load 12 posts but also the first 6 which have already been loaded.

答案1

得分: 0

你的代码很完美。
只需在切片方法中实现分页,当用户点击“显示更多”时增加页面编号,并仅切片“REQUIRED FILES”数据。

你的代码将如下所示:

async function getBlogPosts(blogsPerPage: number, pageNumber: number) {
  const files = fs.readdirSync('posts');

  // 重要提示:在切片之前在这里对文件数组进行排序,以避免重复的帖子...

  const posts = files.slice((pageNumber - 1) * blogsPerPage, pageNumber * blogsPerPage).map((fileName) => {
    const slug = fileName.replace('.md', '');
    const readFile = fs.readFileSync(`posts/${fileName}`, 'utf-8');
    const { data: frontmatter } = matter(readFile);
    return {
      slug,
      frontmatter,
    };
  });

  return posts;
}

现在你可以在你的函数组件中实现一个状态,并像这样调用这个函数:

export default async function Blogs() {
  const [pageNumber, setPageNumber] = useState(0);

  const posts = await getBlogPosts(6, pageNumber);

  // ......

}
英文:

You code is perfect.
Just implement pagination during slice method, increase page number as user clicks show more. and slice REQUIRED FILES data only.

Your code would look like this:

async function getBlogPosts(blogsPerPage:number, pageNumber:number) {
  const files = fs.readdirSync(&#39;posts&#39;);

  !IMPORTANT. sort files array here before slicing, so we wont get repeated posts...

  const posts = files.slice((pageNumber-1)* blogsPerPage,pageNumber*blogsPerPage).map((fileName) =&gt; {
    const slug = fileName.replace(&#39;.md&#39;, &#39;&#39;);
    const readFile = fs.readFileSync(`posts/${fileName}`, &#39;utf-8&#39;);
    const { data: frontmatter } = matter(readFile);
    return {
      slug,
      frontmatter,
    };
  });

  return posts;
}

Now you can implement a state in your functional component and call this function somewhat like this:

export default async function Blogs() {
  const [pageNumber, setPageNumber] = useState(0);

  const posts = await getBlogPosts(6,pageNumber);

  ......
}

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

发表评论

匿名网友

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

确定