~~~js
import debounce from 'lodash/debounce';
export default class Search extends Component {
constructor(props) {
super(props)
this.handleSearch = debounce(this.handleSearch, 500);
}
handleSubmit = (e) => {
e.preventDefault();
this.handleSearch();
}
handleSearch = () => {
...
}
render() {
return (
<form onSubmit={this.handleSubmit}><form>
)
}
}
~~~
这是一段在react类组件中使用节流函数的示例代码,而当你想在函数式组件中使用节流函数时,你可能会自然而然的想要这么做::
~~~js
import React, {useState} from "react";
import debounce from 'lodash/debounce';
const sendQuery = (query) => console.log(`Querying for ${query}`);
const Search = () => {
const [userQuery, setUserQuery] = useState("");
const delayedQuery = debounce(q => sendQuery(q), 500);
const onChange = e => {
setUserQuery(e.target.value);
delayedQuery(e.target.value);
};
return (
<div>
<label>Search:</label>
<input onChange={onChange} value={userQuery} />
</div>
);
}
~~~
但这样子做防抖函数并没有发挥作用,仅仅是把反应时间延后了500毫秒。这是因为函数时组件每次渲染结束之后,内部的变量都会被释放,重新渲染时所有的变量会被重新初始化,产生的结果就是每一次都注册和执行了setTimeout函数。想要得到正确的运行结果,必须以某种方式存储那些本会被删除的变量和方法的引用。很遗憾,没办法直接使用useState去存储,但是我们可以直接构造一个新的hook去解决这个问题。
~~~js
import React, { useState, useEffect } from 'react';
// Our hook
export default function useDebounce(value, delay) {
// State and setters for debounced value
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(
() => {
// Set debouncedValue to value (passed in) after the specified delay
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Return a cleanup function that will be called every time ...
// ... useEffect is re-called. useEffect will only be re-called ...
// ... if value changes (see the inputs array below).
// This is how we prevent debouncedValue from changing if value is ...
// ... changed within the delay period. Timeout gets cleared and restarted.
// To put it in context, if the user is typing within our app's ...
// ... search box, we don't want the debouncedValue to update until ...
// ... they've stopped typing for more than 500ms.
return () => {
clearTimeout(handler);
};
},
// Only re-call effect if value changes
// You could also add the "delay" var to inputs array if you ...
// ... need to be able to change that dynamically.
[value]
);
return debouncedValue;
}
~~~
构造完useDebounce函数后,我们可以这样使用:
~~~js
import React, { useState, useEffect } from 'react';
import useDebounce from './use-debounce';
const sendQuery = (query) => console.log(`Querying for ${query}`);
// Usage
function Search() {
// State and setter for search term
const [searchTerm, setSearchTerm] = useState('');
// State and setter for search results
const [results, setResults] = useState([]);
// State for search status (whether there is a pending API request)
const [isSearching, setIsSearching] = useState(false);
// Now we call our hook, passing in the current searchTerm value.
// The hook will only return the latest value (what we passed in) ...
// ... if it's been more than 500ms since it was last called.
// Otherwise, it will return the previous value of searchTerm.
// The goal is to only have the API call fire when user stops typing ...
// ... so that we aren't hitting our API rapidly.
const debouncedSearchTerm = useDebounce(searchTerm, 500);
// Here's where the API call happens
// We use useEffect since this is an asynchronous action
useEffect(
() => {
// Make sure we have a value (user has entered something in input)
if (debouncedSearchTerm) {
// Set isSearching state
setIsSearching(true);
// Fire off our API call
sendQuery(debouncedSearchTerm);
// Set back to false since request finished
setIsSearching(false);
// Set results state
setResults(results);
} else {
setResults([]);
}
},
// This is the useEffect input array
// Our useEffect function will only execute if this value changes ...
// ... and thanks to our hook it will only change if the original ...
// value (searchTerm) hasn't changed for more than 500ms.
[debouncedSearchTerm]
);
return (
<div>
<label>Search:</label>
<input onChange={e => setSearchTerm(e.target.value) />
</div>
);
}
~~~
上面的方法还是太复杂了,通过使用useRef和useCallback我们可以更简单的去解决这个问题:
~~~js
const SearchFixed = () => {
const [userQuery, setUserQuery] = useState("");
const delayedQuery = useRef(debounce(q => sendQuery(q), 500)).current;
const onChange = e => {
setUserQuery(e.target.value);
delayedQuery(e.target.value);
};
return (
<div>
<label>Search Fixed:</label>
<input onChange={onChange} value={userQuery} />
</div>
);
};
~~~
或是:
~~~js
const SearchFixed = () => {
const [userQuery, setUserQuery] = useState("");
const delayedQuery = useCallback(debounce(q => sendQuery(q), 500), []);
const onChange = e => {
setUserQuery(e.target.value);
delayedQuery(e.target.value);
};
return (
<div>
<label>Search Fixed:</label>
<input onChange={onChange} value={userQuery} />
</div>
);
};
~~~
- 首页
- pm2
- pm2
- pm2 离线安装
- pm2 使用指南
- node
- 正则
- web
- webpack
- 配置
- 优化代码体积
- plugin-proposal-decorators
- webpack 打包原理解析
- babel presets配置 babel7
- 配置路径别名
- 去除开发中的警告信息
- css
- 滚动条
- input自动填充背景色
- 颜色渐变
- scss
- 网页定制光标
- 超出文本显示省略号。。。
- calc兼容性写法
- box-sizing
- clip-path
- 苹果手机页面滑动卡顿
- 字体间距根据父级宽度自适应
- 纯css动态效果
- 清除浮动的三种方法
- 按钮增加闪烁效果
- 字体渐变
- react
- mobx
- 路由
- antd 表格在safari上卡顿
- 项目初始化
- react-antd-mobx-momnet
- 显示字符串中的标签
- antd Select 在搜索精准度
- 路由切换动态过渡效果
- css中图片打包后的路径出错
- antd upload 无法及时更新state
- antd DatePicker设置中文失败
- antd-pro 添加登录页面报错
- new Array创建新数组数据指向相同
- react 页面刷新渲染两次
- useEffect
- Hooks 闭包解决方案
- hooks 方法封装
- Plugin "react" was conflicted between "package.json » eslint-config-react-app
- javascript
- canvas
- 多张图片合成一张
- 排序
- js比较符号==、===
- 运动函数封装(简易、通用)
- 导出表格(excel )
- react使用demo
- xlsx导出excel
- js获取屏幕高度宽度
- toFixed 函数修改
- 获取cookie,url参数
- 奇怪的错误问题
- copy(深拷贝 浅拷贝)
- 导出pdf
- 解决图片失真
- 判断字符串长度(带中文)
- js中 文件、图片二进制和base64的互转
- 读取深度嵌套的json数据
- 手动实现Promise.all
- cookie 删除
- webpack 打包过后的文件报错 regeneratorRuntime is not defined
- 防抖与节流
- react hooks 中使用防抖节流
- 图片懒加载
- 重排和重绘
- 修复部分无法JASON.parse的数据
- react-native
- android-studio 打开调试工具
- 适配全面屏
- node
- 服务端 node + nginx 反向代理
- 生成文件夹目录列表
- mogodb常用操作
- 发布npm包
- cli工具
- 上传文件
- nodejs使用crypto进行加密/解密操作
- mongodb 加入验证之后连接失败
- nextjs使用问题
- node转发http请求
- mongodb 导入导出 备份
- node-sass 安装问题、安装失败等
- npm yarn 安装依赖太慢
- puppeteer 安装问题 centos
- mongoose
- 其他
- 禁止浏览器缓存
- chrome平滑滚动
- pdf预览
- 问题整理
- 资料
- 小程序
- fetch
- cookie 设置跨域资源共享
- taro 小程序
- taro request
- 设置npm镜像
- esbuild the service is no longer running
- 离线地图
- uniapp 转 vue-cli
- 工具
- Excel表格密码保护的解除方法
- vscode(插件)
- vscode 常用代码片段
- vscode 开启tab补全代码
- mac 百度网盘破解
- mysql 重置密码
- chrome 好用的扩展
- Mac/Linux/Windows通过命令调用浏览器打开某网页
- 小链接
- 数据库
- mongo
- sql文件导入
- join 用法
- sql 时间格式化 DATE_FORMAT
- 创建全文检索并分词查询
- 阿里云node-mysql 操作文档
- sql 时间查询
- mysql group查询结果合并为一行
- mysql 锁
- mysql count 同个字段多个结果合并到一行
- 解决Node.js mysql客户端不支持认证协议引发的“ER_NOT_SUPPORTED_AUTH_MODE”问题
- mysql 根据经纬度计算距离
- PHP
- 文件读取
- 接收前端json数据
- 自定义排序
- session 写入失败无法保存
- php 上传大文件$_FILES为空
- base64转图片
- composer.phar 安装东西太慢 切换国内镜像
- laravel sql查询记录
- 解决: Please provide a valid cache path.
- thinkphp开启多应用
- 上传文件报错 Filename cannot be empty
- php curl 报错 curl: (35) SSL connect error
- App
- android未授权错误(Flutter)
- uniapp
- 服务端
- mongodb 定时备份
- mysql 错误
- nginx 转发网络请求
- midwayjs 使用egg-mysql
- https 无法访问
- egg 配置跨域
- 算法实现
- 排序
- 全排列
- 无重复字符的最长子串
- 反转单向链表
- 斐波那契数列
- 有效的括号
- GIT
- git克隆大文件
- 面试整理
- 前端整理
- 大厂高级前端面试题
- 三年大厂面试题
- 面试经验
- 头条it技术工程师
- 每日学习
- 常见的数据结构
- 面试地址汇总
- 练习汇总
- 前端八股文
- mac环境配置
- mac nginx重启报错
- mac 安装redis
- fis配置
- 切换php版本
- Mac OS X下的Oh-My-ZSH安装与配置
- mac 查看端口进程 停止进程
- mac 配置ssh 免密码登录服务器
- navigate 中文破解
- 删除启动台无效文件夹
- 删除顶部图标(卸载后的软件还存在)
- 修复mac 下安装全局依赖失效
- navicate 完美破解 内有下载地址
- nginx 报错 500 "/usr/local/var/run/nginx/client_body_temp/0000000004" failed (13: Permission denied)
- 安装PHP redis扩展
- 安装zsh后 nvm node命令失效
- python
- python 在vscode中编辑,格式化文件总是提示There is no Pip installer available in the selected environment.
- 杂项
- 膝盖修复
- 微信打开网页链接反应巨慢
- chrome 显示http/https完整连接
- doracms
- pdfjs 中文无法显示
- docker
- go
- 指针、指针地址* &
- 脚本
- 京东疯狂的joy脚本
- 2021京东炸年兽
- LINUX