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

210 阅读3分钟

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

文章系列:

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)

这篇文章 开始 编写 标签管理的页面

首先 新建 pages/tag/index.tsx和 pages/tag/index.module.scss分别 存放 标签的 页面和样式

这个页面 我们采用 csr的方式来渲染页面,看看和ssr渲染页面的方式有何不同

在这个页面 我们设计成 全部标签 和关注的标签,页面效果如下:

首先 我们 先 编写接口, 来获取 全部标签和已关注的标签

新建 pages/api/tag/get.ts

1.首先 引入 数据库等的配置

import { NextApiRequest, NextApiResponse } from 'next';
import { withIronSessionApiRoute } from 'iron-session/next';
import { ironOptions } from 'config/index';
import { ISession } from 'pages/api/index';
import { prepareConnection } from 'db/index';
import { Tag } from 'db/entity/index';

2.通过 session 获取 当前用户的id,因为我们需要根据用户id获取该用户的标签数据

const { userId = 0 } = session;

3.链接 标签 数据库的 配置

const db = await prepareConnection();
  const tagRepo = db.getRepository(Tag);

4.首先 获取 全部标签的数据,这个我们只需要 根据 关联 的用户表去 标签的 数据表 查询即可

const allTags = await tagRepo.find({
    relations: ['users'],
  });

5.接下来 获取 关注的标签,关注的标签逻辑是,根据当前用户的id去查询标签数据,这样获取的数据就是该用户关注的标签数据

const followTags = await tagRepo.find({
    relations: ['users'],
    where: (qb: any) => {
      qb.where('user_id = :id', {
        id: Number(userId),
      });
    },
  });

6.最后将 获取的 所有标签数据 和 关注的标签数据 返回

res?.status(200)?.json({
    code: 0,
    msg: '',
    data: {
      followTags,
      allTags,
    },
  });

\

7.接下来 我们在客户端 使用 csr的方式 来获取 全部标签和已关注的标签数据。同followTags和allTags来分别存储全部标签数据和已关注的标签数据

const [followTags, setFollowTags] = useState<ITag[]>();
  const [allTags, setAllTags] = useState<ITag[]>();

useEffect(() => {
    request('/api/tag/get').then((res: any) => {
      if (res?.code === 0) {
        const { followTags = [], allTags = [] } = res?.data || {};
        setFollowTags(followTags);
        setAllTags(allTags);
      }
    })
  }, [needRefresh]);

8.接下来 来渲染 全部标签的数据,这里有个逻辑,就是 显示 关注 还是已关注。当 当前用户id 能够在 接口返回的users中返回的id中能够找打,则表明 当前用户 已关注了 这个标签,则页面上显示 已关注,否则显示关注。当显示已关注的时候,按钮事件则是 取消关注的逻辑,否则则是 关注的逻辑。

<TabPane tab="全部标签" key="all" className={styles.tags}>
        {
            allTags?.map(tag => (
              <div key={tag?.title} className={styles.tagWrapper}>
                <div>{(ANTD_ICONS as any)[tag?.icon]?.render()}</div>
                <div className={styles.title}>{tag?.title}</div>
                <div>{tag?.follow_count} 关注 {tag?.article_count} 文章</div>
                {
                  tag?.users?.find((user) => Number(user?.id) === Number(userId)) ? (
                    <Button type='primary' onClick={() => handleUnFollow(tag?.id)}>已关注</Button>
                  ) : (
                    <Button onClick={() => handleFollow(tag?.id)}>关注</Button>
                  )
                }
              </div>
            ))
          }
        </TabPane>