next.js搭建博客系统-09-ssr渲染文章详情页

311 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第10天,点击查看活动详情

文章系列:

next.js搭建博客系统-01-环境搭建

next.js搭建博客系统-02-实现Layout布局

next.js搭建博客系统-03-登录组件(登录弹窗)

next.js搭建博客系统-04-登录模块(验证码和登录)

next.js搭建博客系统-05-数据库操作

next.js搭建博客系统-06-发布文章(1)

next.js搭建博客系统-07-发布文章(2)

next.js搭建博客系统-08-ssr渲染首页文章列表

next.js搭建博客系统-09-ssr渲染文章详情页

next.js搭建博客系统-10-发布评论

next.js搭建博客系统-11-标签管理(1)

next.js搭建博客系统-12-标签管理(2)

这篇文章开始编写 使用 ssr 渲染文章详情页

这里需要使用 nextjs中的动态路由

在pages/article 新建 [id].tsx,表示 文章详情页的入口文件

同时新建 pages/article/index.module.scss

首先引入 文章 详情页 所需要的 包

import { useState } from 'react';
import Link from 'next/link';
import { Avatar, Input, Button, message, Divider } from 'antd';
import { observer } from 'mobx-react-lite';
import { useStore } from 'store/index';
import MarkDown from 'markdown-to-jsx';
import { format } from 'date-fns';
import { prepareConnection } from 'db/index';
import { Article } from 'db/entity';
import { IArticle } from 'pages/api';
import styles from './index.module.scss';
import request from 'service/fetch';

1.这里使用 mobx-react-lite 第三方库 中的observer 来响应 2.使用 markdown-to-jsx 第三方库的包 来渲染 markdown格式的jsx代码

接下来开始编写

首先通过 url 获取 文章的 id字段

然后根据通过ssr获取文章详情数据

根据id 去数据表中查询当前文章的详情

这里增加一个功能,就是浏览次数,当前查询的时候,浏览次数增加 1 次

export async function getServerSideProps({ params }: any) {
  const articleId = params?.id;
  const db = await prepareConnection();
  const articleRepo = db.getRepository(Article);
  const article = await articleRepo.findOne({
    where: {
      id: articleId,
    },
    relations: ['user', 'comments', 'comments.user'],
  });

  if (article) {
    // 阅读次数 +1
    article.views = article?.views + 1;
    await articleRepo.save(article);
  }

  return {
    props: {
      article: JSON.parse(JSON.stringify(article)),
    },
  };
}

通过以上 ssr 代码就拿到了 当前文章的数据

然后渲染这些基本信息

这里 markdown的内容 使用 markdown-to-jsx 第三方库 来加载

<div className="content-layout">
        <h2 className={styles.title}>{article?.title}</h2>
        <div className={styles.user}>
          <Avatar src={avatar} size={50} />
          <div className={styles.info}>
            <div className={styles.name}>{nickname}</div>
            <div className={styles.date}>
              <div>
                {format(new Date(article?.update_time), 'yyyy-MM-dd hh:mm:ss')}
              </div>
              <div>阅读 {article?.views}</div>
            </div>
          </div>
        </div>
        <MarkDown className={styles.markdown}>{article?.content}</MarkDown>
      </div>

接着增加 是否显示编辑的逻辑

通过store拿到 当前登录的用户信息

const store = useStore();
  const loginUserInfo = store?.user?.userInfo;

当 用户登录的时候,显示编辑按钮

并且 点击 编辑 按钮 跳转到 文章 编辑页面

{Number(loginUserInfo?.userId) === Number(id) && (
                <Link href={`/editor/${article?.id}`}>编辑</Link>
              )}