上集精彩
回顾上集:
上集说完了React如何获取真实的DOM。
本集继续

嘿嘿嘿,俺又回来了😁,最近感冒了,写东西提不起劲来,

这篇文章磕磕巴巴写了两天多,真是一场酣畅淋漓的写作时刻😨
不成熟建议: 俺建议如果有想跟着一起学的朋友的话,不成熟小建议哈,建议示例代码可以试试自己手动敲一下,有不有害俺不知道哈,但肯定是利大于弊滴😃。所以,俺决定了,之后的示例会以图片的形式输出,多见谅,多见谅哈😁
useEffect
useEffect ReactHook函数,用于在React组件中创建中不是由事件引起( 解释下: 不是由事件引起的意思通俗来讲就是不需要用户去做任何手动的操作就可渲染页面 )而是由渲染本身引起的操作,比如发送AJAX请求、更改DOM等。

它有两个参数:
- 参数1:函数或叫它副作用函数,在函数内可以定义你想要执行的操作;
- 参数2(可先参 ):数组,里面放依赖项,不同依赖项会影响第一个参数函数的执行。
当其为一个空数组时,副作用函数只会在组件渲染完毕之后执行一次
。
示例 - AJAX请求:


useEffect依赖项参数


useEffect清楚副作用
在useEffect中编写的由渲染本身引起的对接组件外部的操作,社区经常把它叫做副作用操作,如useEffect中开启一个定时器,想在组件卸载时把定时器清理掉,该过程就是清理副作用。

- 清除副作用函数最常见的执行时机是在组件卸载时自动执行:


点击按钮前,定时器还在继续执行,点击后,定时器就停止了。
自定义Hook函数
自定义Hook是以 use打头的函数
,通过自定义Hook函数实现逻辑的封装和复用。
那咱们用的hook函数都放在哪呢,俺这有个建议,你看可中:

- 在
hooks/useToggle.js
文件中定义hook函数:

- 在App组件中引入并使用该hook:

大致步骤:
- 声明一个以
use打头的函数
- 在函数体内封装可复用的逻辑
- 要把用到的状态或回调return出去(以对象或者数组)
- 在哪个组件中用这个逻辑,就执行这个函数,解构出来状态或回调进行使用
ReactHooks使用规则

案例 - 防哔哩哔哩评论案例
对滴,这就是黑马提供的案例。只是俺把它组件化了,俺个人认为黑马呀,它的课程案例还是非常值得像俺这种小白学的,容易懂。就是这么说,不知道大家有没有看过黑马呀😁
不想一个一个敲的话,可以下载已经组件化好的文件:
百度网盘链接:pan.baidu.com/s/11GBz82yY... ;
- 采用
create-react-app
创建react项目:
cmd
npx create-react-app comment-demo
- 案例需要用到的其他依赖:
cmd
npm i axios classnames dayjs lodash sass uuid json-server
- 接着删删、增增后,初始目录长这样:

- 静态页面长这样:

- 在根目录添加server目录,创建
data.json
死数据文件:json-server
零代码快速搭建本地 RESTful API 的工具,在package.json
添加运行指令
json
"scripts": {
"serve": "json-server server/data.json --port 3001"
},
遍历评论列表
- 启动项目和服务后,通过axios发送请求,lodash设置默认字段排序:

- 抽离出请求列表数据相关的代码,封装成一个hook文件:

- 然后再去使用这个hook:通过子CommentList传父App组件通信


删除评论列表
条件:user.uid === item.user.uid
,意思就是只有自己发的评论才能显示删除,点击删除,删除对应作者的评论,需要一个带参的删除函数:


tab切换并高亮显示
tab切换并高亮显示,map()
遍历tabs数据,设置点击函数,获取type,点击切换效果class样式:


- 基于tabs对评论列表重新排序,采用lodash:列表重新排序就需要使用到commentList,而该属性再App组件中,所以需要使用父传子组件通信


- classnames依赖优化类名控制:

发布评论
-
表单受控绑定
-
react获取DOM,让输入框重新聚焦:

- 点击发布评论:需要用到commentList上个的父传子法子一样的,使用dayjs和uuid依赖自动生成时间和id:

然后在发布按钮通过点击操作该函数。

下集精彩
不能再熬了,再这样就废了,理解一下好不啦😁。

下篇俺会讲到哪些知识点呢: 由于还在感冒中,俺现在已经尽力在更新了。只要懂得这篇的知识点就很棒了。
- 啥是
Redux
; - 啥是 Zustand ;
- 两者有啥区别 ;
