通过番计时器实例学习 React 生命周期函数 componentDidMount
wptr33 2024-12-12 15:23 16 浏览
大家好,今天我们将通过一个实例——番茄计时器,学习下如何使用函数生命周期的一个重要函数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 , 你需要注意这些问题
相关推荐
- 每天一个AI姬,AMD核显用户有福了,AI绘画打破 NVIDIA 显卡垄断
-
使用StableDiffusion进行AI绘画,并不一定只能使用NVIDIA英伟达显卡,甚至,也不一定只能使用独立显卡。今天我们使用AMD6800H核显,并安装了StableDif...
- NETworkManager:功能强大的网络管理与问题排除工具
-
关于NETworkManagerNETworkManager是一款功能强大的网络管理与问题排除工具,该工具完全开源,可以帮助广大研究人员轻松管理目标网络系统并排除网络疑难问题。该工具使用远程桌面、Po...
- AMD也能深度学习+免费AI绘画:StableDiffusion+ROCm部署教程!
-
某国政客扇扇嘴皮子,CN玩硬件和深度学习的圈子里就掀起了一场风暴,这就是著名的嘴皮子效应(误)。没了高性能计算的A100H100倒也能理解,但是美利坚这波把RTX4090禁售了就让人无语了,所以不少做...
- windows 下编译 python_rtmpstream
-
最近在研究数字人,看了大咖的项目(https://github.com/lipku/metahuman-stream),尝试编译此项目的依赖项目python_rtmpstream(https://gi...
- 如何使用 Python 操作 Git 代码?GitPython 入门介绍
-
花下猫语:今天,我在查阅如何用Python操作Gitlab的时候,看到这篇文章,觉得还不错,特分享给大家。文中还提到了其它几种操作Git的方法,后续有机会的话,再陆续分享之~~作者:匿蟒...
- 网上看了不少,终于把ZlmediaKit流媒体框架搭建起来啦
-
你都站在2023年代了,视频通话、视频直播、视频会议、视频监控就是风口浪尖上的猪师兄,只要你学那么一丁点,拿个高薪的工作不过分吧!我也是半瓶子晃荡的,所以路人呀,共学习,同进步!本篇开始,只讲在Lin...
- MacDown:一款 macOS 的强大 Markdown 编辑器
-
大家好,很高兴又见面了,我是"...
- ZLMediaKit安装配置和推拉流
-
一、ZLMediaKit库简介ZLMediaKit是一个基于...
- 大神赞过的:学习 WebAssembly 汇编语言程序设计
-
文/阿里淘系F(x)Team-旭伦随着前端页面变得越来越复杂,javascript的性能问题一再被诟病。而Javascript设计时就不是为了性能优化设计的,这使得浏览器上可以运行的本地语言一...
- 【Docker】部署WVP视频监控平台
-
回来Docker系列,今天将会跟大家分享一则关于开源WVP视频监控平台的搭建。先说结论吧,一开始按照网上说的一步一步搭建没有搭建成功,不知道是版本太旧还是我这边机器有问题,尝试了好几个不同方式的搭建都...
- MongoDB+GridFS存储文件方案
-
GridFS是MongoDB的一个内置功能,它提供一组文件操作的API以利用MongoDB存储文件,GridFS的基本原理是将文件保存在两个Collection中,一个保存文件索引,一个保存文...
- 【开源】强大、创新且直观的 EDA套件
-
今天分享的LibrePCB是...
- Ollama如何制作自己的大模型?
-
背景Llama3发布了,这次用了...
- Ollama使用指南【超全版】
-
一、Ollama快速入门Ollama是一个用于在本地运行大型语言模型的工具,下面将介绍如何在不同操作系统上安装和使用Ollama。官网:https://ollama.comGithub:http...
- 基于区块链的价值共享互联网即时通讯应用平台源码免费分享
-
——————关注转发之后私信回复【源码】即可免费获取到本项目所有源码基于区块链的价值共享互联网即时通讯应用平台,是一个去中心化的任何人都可以使用的通讯网络,是一款基于区块链的价值共享互联网即时通讯AP...
- 一周热门
-
-
C# 13 和 .NET 9 全知道 :13 使用 ASP.NET Core 构建网站 (1)
-
因果推断Matching方式实现代码 因果推断模型
-
git pull命令使用实例 git pull--rebase
-
git 执行pull错误如何撤销 git pull fail
-
面试官:git pull是哪两个指令的组合?
-
git fetch 和git pull 的异同 git中fetch和pull的区别
-
git pull 和git fetch 命令分别有什么作用?二者有什么区别?
-
还可以这样玩?Git基本原理及各种骚操作,涨知识了
-
git pull 之后本地代码被覆盖 解决方案
-
git命令之pull git.pull
-
- 最近发表
-
- 每天一个AI姬,AMD核显用户有福了,AI绘画打破 NVIDIA 显卡垄断
- NETworkManager:功能强大的网络管理与问题排除工具
- AMD也能深度学习+免费AI绘画:StableDiffusion+ROCm部署教程!
- windows 下编译 python_rtmpstream
- 如何使用 Python 操作 Git 代码?GitPython 入门介绍
- 网上看了不少,终于把ZlmediaKit流媒体框架搭建起来啦
- MacDown:一款 macOS 的强大 Markdown 编辑器
- ZLMediaKit安装配置和推拉流
- 大神赞过的:学习 WebAssembly 汇编语言程序设计
- 【Docker】部署WVP视频监控平台
- 标签列表
-
- 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)