React16.7 hooks初探之定时器引发的问题

苏南South 2020-11-13 12:45:22
react 定时器 初探 react16.7 hooks


Hello, thanks for your awesome work on mobx-react! ... an action asynchronously from a componentWillMount hook, the react component will not rerende,本文由@IT·平头哥联盟-首席填坑官∙苏南 分享,公众号:honeyBadger8,webpack4,从0配置到项目搭建,React中的setTimeout、setInterval的注意事项 , react组件 使用setTimeout 定时隐藏 (有demo) 初始化时 展示 1次 图片,1秒后,隐藏图片点击 按钮 展示 1次 图片,1秒后

前言

周末尝试了一下React新的hooks功能,来封装一个组件,遇到一个bug,所以记录一下过程!

报错如下:

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.in Notification

大概意思是组件已经卸载了,但在卸载之后还执行了一个对组件更新的操作,这是一个无效的操作,但它表示应用程序中存在内存泄漏。要修复,请取消useEffect cleanup function.in Notification 中的所有订阅和异步任务
Can't perform a React state update on an unmounted component.Read the Motivation to learn why we’re introducing Hooks to React, react组件 使用setTimeout 定时隐藏 (有demo) 初始化时 展示 1次 图片,1秒后,隐藏图片点击 按钮 展示 1次 图片,1秒后

组件核心代码如下:


function Notification(props){

var timer = null;
const [visible, setVisible] = useState(false);
let {
title,description,duration,theme,onClose,}= props;
let leave = (source='') => {

clearTimeout(timer);
setVisible(false);
console.log("注意这里是 leave方法里,timer的id:"+timer,"事件的来源:",source);
console.log("leave result:",timer);
onClose&&onClose();//首席填坑官∙苏南的专栏 交流:912594095、公众号:honeyBadger8
}
let enter = () => {

setVisible(true);
if( duration > 0 ){

let timer = setTimeout(() => {

console.log(`auto carried out`,timer) //timer Number Id 
leave(`Time to`);
}, duration*1000);
console.log(`enter方法里,timer的id:`,timer) //timer Number Id 
}
}
useEffect(()=>{

enter();
},[])
return (
<div className={
`${
prefixCls}-notice`} style={
{
display:`${
visible?'':'none'}`}}>
{
!!theme&&<p className={
`${
prefixCls}-notice-icon`}><Svg iconId={
`svg-${
theme}`} /></p>}
<div className={
`${
prefixCls}-notice-content`}>
……//首席填坑官∙苏南的专栏 交流:912594095、公众号:honeyBadger8
</div>
<p className={
`${
prefixCls}-notice-colse`} title="关闭" onClick={
()=>leave("手动点击的关闭")}><Svg/></p>
</div>
);
};

简单分析:

  • 首先useEffect方法,是react新增的,它是componentDidMountcomponentDidUpdatecomponentWillUnmount三个生命周期的合集,
  • 也就是之前的写法,上面三生命周期里会执行到的操作,useEffect都会去做;
enter、leave方法
  • 很好理解,进场出场两函数,
  • 进场:加了个定时器,在N秒后执行出场即leave方法,这个逻辑是正常的,
  • 问题就出在手动执行leave,也就是onclick事件上,
问题原因:
  • 其实就是在点击事件的时候,没有获取到 timer的id,导致了定时器没有清除掉;
    !!看图说话:

React v16.7 "Hooks" - What to Expect -点击累加的计数器,公众号:honeyBadger8,从零开始实现一个React(四):异步的setState

解决思路:
  • 当然是先看文档,hooks对我来说也是个新玩意,不会~
  • 1、useEffect方法里return 一个方法,它是可以在组件卸载时执行的,
  • 2、清除定时器它有自己的方式,const intervalRef = useRef();指定赋值后能同步更新,之前的timer手动执行没有拿到timer所以没有清除掉;

点击累加的计数器,公众号:honeyBadger8,首席填坑官∙苏南的专栏 交流:912594095、公众号:honeyBadger8,React Hooks Rewriting - Less Early Impressions : javascript - Reddit

参考链接:

英文的没有找到
英文的也补一下吧
github也有人提到这个问题,学习了

完美解决:

React v16.7 "Hooks" - What to Expect - 知乎,公众号:honeyBadger8,We bring you one new React hook code recipe per day so you can learn how ... a timeout to stop things when duration time elapses timerStop = setTimeout(()


function Notification(props){

var timer = null;
const [visible, setVisible] = useState(false);
let {
title,description,duration,theme,onClose,}= props;
const intervalRef = useRef(null);
let leave = (source='') => {

clearTimeout(intervalRef.current);
setVisible(false);
console.log("leave result:",source,intervalRef);
onClose&&onClose();
}
let enter = () => {

setVisible(true);
if( duration > 0 ){

let id = setTimeout(() => {

console.log(`auto carried out`,intervalRef) //timer Number Id 
leave(`Time to`);
}, duration*1000);
intervalRef.current = id;
}
}
useEffect(()=>{

enter();
return ()=>clearTimeout(intervalRef.current);
},[])
return (
<div className={
`${
prefixCls}-notice`} style={
{
display:`${
visible?'':'none'}`}}>
{
!!theme&&<p className={
`${
prefixCls}-notice-icon`}><Svg iconId={
`svg-${
theme}`} /></p>}
<div className={
`${
prefixCls}-notice-content`}>
……
</div>
<p className={
`${
prefixCls}-notice-colse`} title="关闭" onClick={
()=>leave("手动点击的关闭")}><Svg/></p>
</div>
);
};
欢迎关注公号,支持一下我们,谢谢!

宝剑锋从磨砺出,梅花香自苦寒来,做有温度的攻城狮!,公众号:honeyBadger8

热门推荐

作者:苏南 - 首席填坑官

链接:https://www.susouth.com/other/2018/12/05/shared/

交流:912594095、公众号:honeyBadger8

本文原创,著作权归作者所有。商业转载请联系@IT·平头哥联盟获得授权,非商业转载请注明原链接及出处。

版权声明
本文为[苏南South]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43254766/article/details/84842106

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple