通过番计时器实例学习 React 生命周期函数 componentDidMount
wptr33 2024-12-12 15:23 21 浏览
大家好,今天我们将通过一个实例——番茄计时器,学习下如何使用函数生命周期的一个重要函数componentDidMount():componentDidMount(),在组件加载完成, render之后进行调用,只会执行一次。
番茄工作法
在介绍前我们首先了解下什么是番茄工作法,有利于我们完成这个实例,番茄工作法是简单易行的[时间管理]方法,使用番茄工作法,选择一个待完成的任务,将番茄时间设为25分钟,专注工作,中途不允许做任何与该任务无关的事,直到番茄时钟响起,然后在纸上画一个X短暂休息一下(5分钟就行),每4个番茄时段多休息一会儿。关于详细的介绍可以查看头条百科——https://byte.baike.com/cwiki/番茄工作法&fr=toutiao?tt_from=copy_link&utm_source=copy_link&utm_medium=toutiao_ios&utm_campaign=client_share
首先看看番茄计时器长啥样
下图就是我们要制作的简易番茄计时器,默认计时器为25分钟,界面上有三个按钮,分别是工作、短时间休息、长时间休息,用来启动任务计时器。
创建番茄计时器
1、基于前面几节我们创建的项目,我们在 component 文件夹内新建一个 Pomodaro 的文件夹,然后新建 Timer.js 和 Timer.css 两个文件,首先我们来看看 Timer.js 文件的基本结构,示例代码如下:
import React, { Component } from 'react';
import './Timer.css';
class Timer extends Component {
constructor() {
super();
}
componentDidMount() {
}
render() {
return (
<div className="Pomodoro">
</div>
);
}
}
export default Timer;
// File: src/components/Pomodoro/Timer.js
2、接下来,我们需要在构造函数方法里 constructor() 初始化我们本地数据状态,在这里我们初始化当前时间 time 和 alert(当任务时间到了,系统的提醒信息) 这两个值,同时初始化一些常量设置,比如工作时间 defaultTime、短暂休息时间 shortBreak 、长时间休息 longBreak,其示例代码如下 :
constructor() {
super();
// Initial State
this.state = {
alert: {
type: '',
message: ''
},
time: 0
};
// Defined times for work, short break and long break...
this.times = {
defaultTime: 1500, // 25 min
shortBreak: 300, // 5 min
longBreak: 900 // 15 min
};
}
3、然后我们调用生命周期函数 componentDidMount() , 即在组件加载完成,render() 之后调用,这个方法只会触发一次,在这个例子中 ,我们将 time 的数值状态初始化为1500秒,即25分钟,在这里我们调用了初始化默认时间的方法 setDefaultTime() 方法 。
componentDidMount() {
// Set default time when the component mounts
this.setDefaultTime();
}
setDefaultTime = () => {
// Default time is 25 min
this.setState({
time: this.times.defaultTime
});
}
4、完成了这些基本的定义后,我们需要呈现组件的界面 ,我们的render()方法示例代码如下:
render() {
const { alert: { message, type }, time } = this.state;
return (
<div className="Pomodoro">
<div className={`alert ${type}`}>
{message}
</div>
<div className="timer">
{this.displayTimer(time)}
</div>
<div className="types">
<button
className="start"
onClick={this.setTimeForWork}
>
Start Working
</button>
<button
className="short"
onClick={this.setTimeForShortBreak}
>
Short Break
</button>
<button
className="long"
onClick={this.setTimeForLongBreak}
>
Long Break
</button>
</div>
</div>
);
};
5、从上述代码,我们可以看出我们JSX代码很简单,我们定义变量来接收本地数据状态的值,提醒消息、类型及任务时间,当用户的任务时间到达时,我们用一块div区域展示提醒信息。你也许会注意到,这里我们使用了displayTimer() 方法展示计时器信息,这里我们传入的参数是秒,其将会格式成 mm:ss 的形式,最后我们在界面里添加了几个按钮,用于设置任务的计数器,比如开始工作25分钟,短暂休息5分钟,或者长时间休息15分钟,我们在任务按钮上,分别定义了相关的方法事件,接下来我们要完成这些事件方法。
6、首先我们来看看setTimeForWork()、setTimeForShortBreak() 和 setTimeForLongBreak() 这三个方法,这三个 方法主要作用就是更新任务类型、提醒信息及任务时间,在每个方法里我们在函数返回时触发调用 setTime() 函数用于重置任务时间计时器。这三个方法的示例代码如下:
setTimeForWork = () => {
this.setState({
alert: {
type: 'work',
message: 'Working!'
}
});
return this.setTime(this.times.defaultTime);
}
setTimeForShortBreak = () => {
this.setState({
alert: {
type: 'shortBreak',
message: 'Taking a Short Break!'
}
});
return this.setTime(this.times.shortBreak);
}
setTimeForLongBreak = () => {
this.setState({
alert: {
type: 'longBreak',
message: 'Taking a Long Break!'
}
});
return this.setTime(this.times.longBreak);
}
7、在前面文章里,我们学习了箭头函数里this的穿透作用,这意味着我们不需要在构造函数中进行绑定。现在我们来看看 setTime() 函数是如何定义的。
setTime = newTime => {
this.restartInterval();
this.setState({
time: newTime
});
}
8、从上述代码你可以看出,我们调用一个 restartInterval() 方法重置任务时间,我们通过 newTime 传参的形式更新了 time 状态的值。接下来我们来实现 restartInterval() 方法 ,首先清理计时器 ,然后每秒执行计时器的相关方法,示例代码如下:
restartInterval = () => {
// Clearing the interval
clearInterval(this.interval);
// Execute countDown function every second
this.interval = setInterval(this.countDown, 1000);
}
9、上述代码 clearInterval(this.interval) 函数的作用就是清理计时器,因为我们进行任务切换时,需要重置计时器,然后调用 countDown 计时方法,其代码示例如下:
countDown = () => {
// If the time reach 0 then we display Buzzzz! alert.
if (this.state.time === 0) {
this.setState({
alert: {
type: 'buz',
message: 'Buzzzzzzzz!'
}
});
} else {
// We decrease the time second by second
this.setState({
time: this.state.time - 1
});
}
}
10、最后我们来完成该组件的最后一个方法,其功能就是把时间格式化成 mm:ss 的形式,示例代码如下:
displayTimer(seconds) {
// Formatting the time into mm:ss
const m = Math.floor(seconds % 3600 / 60);
const s = Math.floor(seconds % 3600 % 60);
return `${m < 10 ? '0' : ''}${m}:${s < 10 ? '0' : ''}${s}`;
}
11、最终我们完成组件代码如下所示:
import React,{Component} from "react";
import './Timer.css';
class Timer extends Component{
constructor() {
super();
this.state={
alert:{
type:'',
message:''
},
time:0
};
this.times = {
defaultTime:1500,// 25 min
shortBreak:300, // 5 min
longBreak:900
}
};
componentDidMount() {
this.setDefaultTime();
}
setDefaultTime = () =>{
this.setState({
time: this.times.defaultTime
});
};
setTime = newTime => {
this.restartInterval();
this.setState({
time:newTime
});
};
restartInterval = () => {
clearInterval(this.interval);
this.interval = setInterval(this.countDown,1000);
};
countDown = ()=>{
// If the time reach 0 then we display Buzzzzzz! alert
if(this.state.time===0){
this.setState({
alert:{
type:'buz',
message:'Buzzzzzzzz!'
}
})
} else {
// We decrease the time second by second
this.setState({
time:this.state.time-1
})
}
};
setTimeForWork = ()=> {
this.setState({
alert:{
type:'work',
message:'Working'
}
});
return this.setTime(this.times.defaultTime);
};
setTimeForShortBreak = () =>{
this.setState({
alert:{
type:'shortBreak',
message:'Taking a short Break!'
}
});
return this.setTime(this.times.shortBreak);
};
setTimeForLongBreak = ()=>{
this.setState({
alert:{
type:'longBreak',
message:'Taking a Long Break!'
}
});
return this.setTime(this.times.longBreak);
};
displayTimer(seconds){
const m = Math.floor(seconds % 3600 / 60);
const s = Math.floor(seconds % 3600 % 60);
return `${m < 10 ? '0' : ''} ${m} : ${ s < 10 ? '0' : ''} ${s}`;
}
render() {
const { alert : {message , type },time } =this.state;
return(
<div className="Pomodoro">
<div className={`alert ${type}`}>
{message}
</div>
<div className="timer">
{this.displayTimer(time)}
</div>
<div className="types">
<button
className="start"
onClick={this.setTimeForWork}
>
Start Working
</button>
<button
className="short"
onClick={this.setTimeForShortBreak}
>
short Break
</button>
<button
className="long"
onClick={this.setTimeForLongBreak}
>
Long Break
</button>
</div>
</div>
);
}
}
export default Timer;
12、组件代码完成后,最后一步就是添加样式了,以下代码是番茄计时器的css代码,你可以根据需要自行修改:
.Pomodoro {
padding: 50px;
}
.Pomodoro .timer {
font-size: 100px;
font-weight: bold;
}
.Pomodoro .alert {
font-size: 20px;
padding: 50px;
margin-bottom: 20px;
}
.Pomodoro .alert.work {
background: #5da423;
}
.Pomodoro .alert.shortBreak {
background: #f4ad42;
}
.Pomodoro .alert.longBreak {
background: #2ba6cb;
}
.Pomodoro .alert.buz {
background: #c60f13;
}
.Pomodoro button {
background: #2ba6cb;
border: 1px solid #1e728c;
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5) inset;
color: white;
cursor: pointer;
display: inline-block;
font-size: 14px;
font-weight: bold;
line-height: 1;
margin: 50px 10px 0px 10px;
padding: 10px 20px 11px;
position: relative;
text-align: center;
text-decoration: none;
}
.Pomodoro button.start {
background-color: #5da423;
border: 1px solid #396516;
}
.Pomodoro button.short {
background-color: #f4ad42;
border: 1px solid #dd962a;
}
最后不要忘记将组件引入到App.js文件中进行调用,如果你正确完成上述操作,就能看到你的计时器如下图所示:
工作任务状态
短暂休息状态
长时间休息状态
任务结束提醒
小节
本篇文章的内容就和大家分享到这里,想必大家对这个函数 componentDidMount() 的用法了解了吧,因为它只会被执行一次,在页面挂载成功的时候执行,我们的请求一般是放在componentDidMount 生命周期函数中进行调用,当然你也可以放在componentWillMount 函数中。下篇本系列文章,我将和大家继续通过实例的形式介绍生命周期函数shouldComponentUpdate(),敬请期待...
《 React 手册》系列文章
「React 手册」在 React 项目中使用 ES6,你需要了解这些(一)
「React 手册 」在 Windows 下使用 React , 你需要注意这些问题
相关推荐
- 「网络安全」JAVA代码审计——XXE外部实体注入
-
一、WEB安全部分想要了解XXE,在那之前需要了解XML的相关基础二、XML基础...
- Web前端面试题目及答案汇总(web前端面试题最新)
-
Web前端面试题目及答案汇总来源:极客头条以下是收集一些面试中经常会遇到的经典面试题以及自己面试过程中无法解决的问题,通过对知识的整理以及经验的总结,重新巩固自身的前端基础知识,如有错误或更好的答案,...
- 什么是脚本文件?与可执行文件有什么不同?
-
今天的内容是脚本文件和可执行文件是两种不同类型的计算机文件,它们在结构和执行方式上有显著区别。脚本文件:定义与特性...
- 20个实用Python运维脚本(收藏级)(python 运维工具)
-
系统环境:支持Linux(Ubuntu/CentOS/Debian)和Windows...
- 2026年前每个开发者都应该学习的技能
-
优秀开发者...
- Linux 如何每 5、10、15 或 30 分钟运行一次 Cron 作业?
-
在Linux系统中,Cron是一个强大的工具,用于自动化重复性任务。通过合理配置...
- Shell脚本编程进阶实战:从入门到高效自动化
-
Shell脚本编程进阶实战:从入门到高效自动化一、参数处理进阶:打造专业级CLI工具1.高级参数解析示例...
- 在Bash中按分隔符拆分字符串的方法
-
技术背景在Bash脚本编程中,经常会遇到需要按特定分隔符拆分字符串的需求,例如处理CSV文件、解析日志等。掌握字符串拆分的方法对于数据处理和脚本自动化非常重要。...
- 程序员用5分钟,把一个400多MB的苹果安装包削掉了187MB
-
丰色发自凹非寺量子位|公众号QbitAI前些日子,一个...
- 如何在 Windows 上编写批处理脚本
-
你知道如何使用命令提示符吗?如果这样做,您可以编写一个批处理文件。在最简单的形式中,批处理文件(或批处理脚本)是双击文件时执行的几个命令的列表。批处理文件一直回到DOS,但仍然适用于现代版本的Win...
- 一文搞懂shell脚本(shell脚本应用实战)
-
一文搞懂shell脚本1、shell脚本介绍什么是shell脚本...
- 一文讲清ShellScript脚本编程知识
-
摘要:本文详尽地讲述了ShellScript的基础内容,还有它在Linux系统里的运用情况,涵盖了它的基本语法、常用的命令以及高级的功能。ShellScript可是一种简单又非常实用的编...
- 在Bash脚本中获取自身所在目录的方法
-
技术背景在使用Bash脚本时,有时需要获取脚本自身所在的目录。比如,当脚本作为另一个应用程序的启动器时,需要将工作目录更改为脚本所在的目录,以便对该目录中的文件进行操作。然而,由于脚本的调用方式多样(...
- shell中如何确定脚本的位置?这篇文章告诉你
-
我想从同一个位置读取一些配置文件,如何确定脚本的位置?。这个问题的出现主要是由两个原因引发的:一是您希望将脚本的数据或配置进行外部化,因此需要一种方式来寻找这些外部资源;二是您的脚本需要对某些捆绑资源...
- bash shell 语法(bash命令用法)
-
下面是**Shell(Bash)语法的常用知识点总结**,适合初学者和日常脚本编写参考。内容涵盖变量、判断、循环、函数、重定向、正则、数组等常见用法。---#Shell(Bash)语法速查总结...
- 一周热门
-
-
C# 13 和 .NET 9 全知道 :13 使用 ASP.NET Core 构建网站 (1)
-
因果推断Matching方式实现代码 因果推断模型
-
git pull命令使用实例 git pull--rebase
-
面试官:git pull是哪两个指令的组合?
-
git 执行pull错误如何撤销 git pull fail
-
git pull 和git fetch 命令分别有什么作用?二者有什么区别?
-
git fetch 和git pull 的异同 git中fetch和pull的区别
-
git pull 之后本地代码被覆盖 解决方案
-
还可以这样玩?Git基本原理及各种骚操作,涨知识了
-
git命令之pull git.pull
-
- 最近发表
- 标签列表
-
- git pull (33)
- git fetch (35)
- mysql insert (35)
- mysql distinct (37)
- concat_ws (36)
- java continue (36)
- jenkins官网 (37)
- mysql 子查询 (37)
- python元组 (33)
- mybatis 分页 (35)
- vba split (37)
- redis watch (34)
- python list sort (37)
- nvarchar2 (34)
- mysql not null (36)
- hmset (35)
- python telnet (35)
- python readlines() 方法 (36)
- munmap (35)
- docker network create (35)
- redis 集合 (37)
- python sftp (37)
- setpriority (34)
- c语言 switch (34)
- git commit (34)