飞道的博客

「React 基础」组件生命周期函数componentDidMount()介绍

351人阅读  评论(0)

家好,今天我们将通过一个实例——番茄计时器,学习下如何使用函数生命周期的一个重要函数componentDidMount():在组件加载完成, render之后进行调用,只会执行一次。

番茄工作法

在介绍前我们首先了解下什么是番茄工作法,有利于我们完成这个实例,番茄工作法是简单易行的[时间管理]方法,使用番茄工作法,选择一个待完成的任务,将番茄时间设为25分钟,专注工作,中途不允许做任何与该任务无关的事,直到番茄时钟响起,然后在纸上画一个X短暂休息一下(5分钟就行),每4个番茄时段多休息一会儿。关于详细的介绍可以查看百度百科。

首先看看番茄计时器长啥样

下图就是我们要制作的简易番茄计时器,默认计时器为25分钟,界面上有三个按钮,分别是工作、短时间休息、长时间休息,用来启动任务计时器。

创建番茄计时器

1、基于前面几节我们创建的项目,我们在 component 文件夹内新建一个 Pomodaro 的文件夹,然后新建 Timer.js 和 Timer.css 两个文件,首先我们来看看 Timer.js 文件的基本结构,示例代码如下:


   
  1. import React, { Component } from 'react';
  2. import './Timer.css';
  3. class Timer extends Component {
  4. constructor() {
  5. super();
  6. }
  7. componentDidMount() {
  8. }
  9. render() {
  10. return (
  11. <div className= "Pomodoro">
  12. </div>
  13. );
  14. }
  15. }
  16. export default Timer;
  17. // File: src/components/Pomodoro/Timer.js

2、接下来,我们需要在构造函数方法里 constructor() 初始化我们本地数据状态,在这里我们初始化当前时间 time 和 alert(当任务时间到了,系统的提醒信息) 这两个值,同时初始化一些常量设置,比如工作时间 defaultTime、短暂休息时间 shortBreak 、长时间休息 longBreak,其示例代码如下 :


   
  1. constructor() {
  2. super();
  3. // Initial State
  4. this.state = {
  5. alert: {
  6. type: '',
  7. message: ''
  8. },
  9. time: 0
  10. };
  11. // Defined times for work, short break and long break...
  12. this.times = {
  13. defaultTime: 1500, // 25 min
  14. shortBreak: 300, // 5 min
  15. longBreak: 900 // 15 min
  16. };
  17. }

3、然后我们调用生命周期函数 componentDidMount() , 即在组件加载完成,render() 之后调用,这个方法只会触发一次,在这个例子中 ,我们将 time 的数值状态初始化为1500秒,即25分钟,在这里我们调用了初始化默认时间的方法 setDefaultTime() 方法 。


   
  1. componentDidMount() {
  2. // Set default time when the component mounts
  3. this.setDefaultTime();
  4. }
  5. setDefaultTime = () => {
  6. // Default time is 25 min
  7. this.setState({
  8. time: this.times.defaultTime
  9. });
  10. }

4、完成了这些基本的定义后,我们需要呈现组件的界面 ,我们的render()方法示例代码如下:


   
  1. render() {
  2. const { alert: { message, type }, time } = this.state;
  3. return (
  4. <div className= "Pomodoro">
  5. <div className={`alert ${type}`}>
  6. {message}
  7. </div>
  8. <div className= "timer">
  9. {this.displayTimer(time)}
  10. </div>
  11. <div className= "types">
  12. <button
  13. className= "start"
  14. onClick={this.setTimeForWork}
  15. >
  16. Start Working
  17. </button>
  18. <button
  19. className= "short"
  20. onClick={this.setTimeForShortBreak}
  21. >
  22. Short Break
  23. </button>
  24. <button
  25. className= "long"
  26. onClick={this.setTimeForLongBreak}
  27. >
  28. Long Break
  29. </button>
  30. </div>
  31. </div>
  32. );
  33. };

5、从上述代码,我们可以看出我们JSX代码很简单,我们定义变量来接收本地数据状态的值,提醒消息、类型及任务时间,当用户的任务时间到达时,我们用一块div区域展示提醒信息。你也许会注意到,这里我们使用了displayTimer() 方法展示计时器信息,这里我们传入的参数是秒,其将会格式成 mm:ss 的形式,最后我们在界面里添加了几个按钮,用于设置任务的计数器,比如开始工作25分钟,短暂休息5分钟,或者长时间休息15分钟,我们在任务按钮上,分别定义了相关的方法事件,接下来我们要完成这些事件方法。

6、首先我们来看看setTimeForWork()、setTimeForShortBreak() 和 setTimeForLongBreak() 这三个方法,这三个方法主要作用就是更新任务类型、提醒信息及任务时间,在每个方法里我们在函数返回时触发调用 setTime() 函数用于重置任务时间计时器。这三个方法的示例代码如下:


   
  1. setTimeForWork = () => {
  2. this.setState({
  3. alert: {
  4. type: 'work',
  5. message: 'Working!'
  6. }
  7. });
  8. return this.setTime(this.times.defaultTime);
  9. }
  10. setTimeForShortBreak = () => {
  11. this.setState({
  12. alert: {
  13. type: 'shortBreak',
  14. message: 'Taking a Short Break!'
  15. }
  16. });
  17. return this.setTime(this.times.shortBreak);
  18. }
  19. setTimeForLongBreak = () => {
  20. this.setState({
  21. alert: {
  22. type: 'longBreak',
  23. message: 'Taking a Long Break!'
  24. }
  25. });
  26. return this.setTime(this.times.longBreak);
  27. }

7、在前面文章里,我们学习了箭头函数里this的穿透作用,这意味着我们不需要在构造函数中进行绑定。现在我们来看看 setTime() 函数是如何定义的。


   
  1. setTime = newTime => {
  2. this.restartInterval();
  3. this.setState({
  4. time: newTime
  5. });
  6. }

8、从上述代码你可以看出,我们调用一个 restartInterval() 方法重置任务时间,我们通过 newTime 传参的形式更新了 time 状态的值。接下来我们来实现 restartInterval() 方法 ,首先清理计时器 ,然后每秒执行计时器的相关方法,示例代码如下:


   
  1. restartInterval = () => {
  2. // Clearing the interval
  3. clearInterval(this.interval);
  4. // Execute countDown function every second
  5. this.interval = setInterval(this.countDown, 1000);
  6. }

9、上述代码 clearInterval(this.interval) 函数的作用就是清理计时器,因为我们进行任务切换时,需要重置计时器,然后调用 countDown 计时方法,其代码示例如下:


   
  1. countDown = () => {
  2. // If the time reach 0 then we display Buzzzz! alert.
  3. if (this.state.time === 0) {
  4. this.setState({
  5. alert: {
  6. type: 'buz',
  7. message: 'Buzzzzzzzz!'
  8. }
  9. });
  10. } else {
  11. // We decrease the time second by second
  12. this.setState({
  13. time: this.state.time - 1
  14. });
  15. }
  16. }

10、最后我们来完成该组件的最后一个方法,其功能就是把时间格式化成 mm:ss 的形式,示例代码如下:


   
  1. displayTimer(seconds) {
  2. // Formatting the time into mm:ss
  3. const m = Math.floor(seconds % 3600 / 60);
  4. const s = Math.floor(seconds % 3600 % 60);
  5. return `${m < 10 ? '0' : ''}${m}:${s < 10 ? '0' : ''}${s}`;
  6. }

11、最终我们完成组件代码如下所示:


   
  1. import React,{Component} from "react";
  2. import './Timer.css';
  3. class Timer extends Component{
  4. constructor() {
  5. super();
  6. this.state={
  7. alert:{
  8. type: '',
  9. message: ''
  10. },
  11. time: 0
  12. };
  13. this.times = {
  14. defaultTime: 1500, // 25 min
  15. shortBreak: 300, // 5 min
  16. longBreak: 900
  17. }
  18. };
  19. componentDidMount() {
  20. this.setDefaultTime();
  21. }
  22. setDefaultTime = () =>{
  23. this.setState({
  24. time: this.times.defaultTime
  25. });
  26. };
  27. setTime = newTime => {
  28. this.restartInterval();
  29. this.setState({
  30. time:newTime
  31. });
  32. };
  33. restartInterval = () => {
  34. clearInterval(this.interval);
  35. this.interval = setInterval(this.countDown, 1000);
  36. };
  37. countDown = ()=>{
  38. // If the time reach 0 then we display Buzzzzzz! alert
  39. if(this.state.time=== 0){
  40. this.setState({
  41. alert:{
  42. type: 'buz',
  43. message: 'Buzzzzzzzz!'
  44. }
  45. })
  46. } else {
  47. // We decrease the time second by second
  48. this.setState({
  49. time:this.state.time -1
  50. })
  51. }
  52. };
  53. setTimeForWork = ()=> {
  54. this.setState({
  55. alert:{
  56. type: 'work',
  57. message: 'Working'
  58. }
  59. });
  60. return this.setTime(this.times.defaultTime);
  61. };
  62. setTimeForShortBreak = () =>{
  63. this.setState({
  64. alert:{
  65. type: 'shortBreak',
  66. message: 'Taking a short Break!'
  67. }
  68. });
  69. return this.setTime(this.times.shortBreak);
  70. };
  71. setTimeForLongBreak = ()=>{
  72. this.setState({
  73. alert:{
  74. type: 'longBreak',
  75. message: 'Taking a Long Break!'
  76. }
  77. });
  78. return this.setTime(this.times.longBreak);
  79. };
  80. displayTimer(seconds){
  81. const m = Math.floor(seconds % 3600 / 60);
  82. const s = Math.floor(seconds % 3600 % 60);
  83. return `${m < 10 ? '0' : ''} ${m} : ${ s < 10 ? '0' : ''} ${s}`;
  84. }
  85. render() {
  86. const { alert : {message , type },time } =this.state;
  87. return(
  88. <div className= "Pomodoro">
  89. <div className={`alert ${type}`}>
  90. {message}
  91. </div>
  92. <div className= "timer">
  93. {this.displayTimer(time)}
  94. </div>
  95. <div className= "types">
  96. <button
  97. className= "start"
  98. onClick={this.setTimeForWork}
  99. >
  100. Start Working
  101. </button>
  102. <button
  103. className= "short"
  104. onClick={this.setTimeForShortBreak}
  105. >
  106. short Break
  107. </button>
  108. <button
  109. className= "long"
  110. onClick={this.setTimeForLongBreak}
  111. >
  112. Long Break
  113. </button>
  114. </div>
  115. </div>
  116. );
  117. }
  118. }
  119. export default Timer;

12、组件代码完成后,最后一步就是添加样式了,以下代码是番茄计时器的css代码,你可以根据需要自行修改:


   
  1. .Pomodoro {
  2. padding: 50px;
  3. }
  4. .Pomodoro .timer {
  5. font-size: 100px;
  6. font-weight: bold;
  7. }
  8. .Pomodoro .alert {
  9. font-size: 20px;
  10. padding: 50px;
  11. margin-bottom: 20px;
  12. }
  13. .Pomodoro .alert.work {
  14. background: #5da423;
  15. }
  16. .Pomodoro .alert.shortBreak {
  17. background: #f4ad42;
  18. }
  19. .Pomodoro .alert.longBreak {
  20. background: #2ba6cb;
  21. }
  22. .Pomodoro .alert.buz {
  23. background: #c60f13;
  24. }
  25. .Pomodoro button {
  26. background: #2ba6cb;
  27. border: 1px solid #1e728c;
  28. box-shadow: 0 1px 0 rgba( 255, 255, 255, 0.5) inset;
  29. color: white;
  30. cursor: pointer;
  31. display: inline-block;
  32. font-size: 14px;
  33. font-weight: bold;
  34. line-height: 1;
  35. margin: 50px 10px 0px 10px;
  36. padding: 10px 20px 11px;
  37. position: relative;
  38. text-align: center;
  39. text-decoration: none;
  40. }
  41. .Pomodoro button.start {
  42. background-color: #5da423;
  43. border: 1px solid #396516;
  44. }
  45. .Pomodoro button.short {
  46. background-color: #f4ad42;
  47. border: 1px solid #dd962a;
  48. }

最后不要忘记将组件引入到App.js文件中进行调用,如果你正确完成上述操作,就能看到你的计时器如下图所示:

工作任务状态

短暂休息状态

长时间休息状态

任务结束提醒

小节

本篇文章的内容就和大家分享到这里,想必大家对这个函数 componentDidMount() 的用法了解了吧,因为它只会被执行一次,在页面挂载成功的时候执行,我们的Ajax数据请求一般是放在componentDidMount 生命周期函数中进行调用,当然你也可以放在componentWillMount 函数中。下篇本系列文章,我将和大家继续通过实例的形式介绍生命周期函数shouldComponentUpdate(),敬请期待...

React基础相关文章

专注分享当下最实用的前端技术。关注前端达人,与达人一起学习进步!

长按关注"前端达人"


转载:https://blog.csdn.net/Ed7zgeE9X/article/details/104177857
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场