web前端全系列 教程
1839个小节阅读:2243k
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
每个 effect 都可以返回一个清除函数。它们都属于 effect 的一部分,我们期望这个清除函数在组件被卸载的时候被调用。
xxxxxxxxxx
//App.js
import React, { useState } from 'react';
import Counter1 from './classes/Counter';
import Counter2 from './hooks/Counter';
export default function App(){
const [showCounter1,setShowCounter1]=useState(true)
const [showCounter2,setShowCounter2]=useState(true)
return <div>
<button onClick={()=>setShowCounter1(false)}>卸载Couter1</button>
<button onClick={()=>setShowCounter2(false)}>卸载Couter2</button>
{showCounter1&&<Counter1/>}
{showCounter2&&<Counter2/>}
</div>
}
xxxxxxxxxx
//classes/Counter.js
import React, { Component } from 'react'
export default class Counter extends Component {
constructor(props) {
super(props)
this.state = { count: 0 ,time:new Date().toLocaleTimeString()}
this.inputRef=React.createRef()
}
componentDidMount(){
this.inputRef.current.value=`点击了${this.state.count}次`
this.timer=setInterval(()=>{
console.log(new Date().toLocaleTimeString())
this.setState({time:new Date().toLocaleTimeString()})
},1000)
}
componentDidUpdate(){
this.inputRef.current.value=`点击了${this.state.count}次`
}
componentWillUnmount(){
//组件卸载的时候清除定时器
clearInterval(this.timer)
}
render() {
return (
<div>
我是一个使用class定义的组件<br />
<button onClick={() => this.setState({ count: this.state.count + 1 })}>变数</button>
<h3>数量:{this.state.count}</h3>
<input ref={this.inputRef}/>
<h3>现在是:{this.state.time}</h3>
</div>
)
}
}
xxxxxxxxxx
//hooks/Counter.js
import React, { useState, useEffect } from 'react'
export default function Counter() {
// 声明一个叫 “count” 的 state 变量。useState返回一个数组
const [count, setCount] = useState(0)
//声明叫做color的state变量
const [color, setColor] = useState('red')
const [time, setTime] = useState(new Date().toLocaleTimeString())
const inputRef = React.createRef()
//接收一个函数
useEffect(() => {
console.log('effect')
inputRef.current.value = `点击了${count}次`
const timer = setInterval(() => {
console.log(new Date().toLocaleTimeString())
setTime(new Date().toLocaleTimeString() )
}, 1000)
//通过return 返回的回调函数会在组件卸载时调用
return () => {
clearInterval(timer)
}
})
return (
<div>
我是使用hook的组件
<br />
<button onClick={() => setCount(count + 1)}>变量</button>
<button onClick={() => setColor('blue')}>变色</button>
<h3 style={{ color }}>数量:{count}</h3>
<input ref={inputRef} />
<h3>现在的时间是:{time}</h3>
</div>
)
}
提示:
你可以把
useEffect
Hook 看做componentDidMount
,componentDidUpdate
,componentWillUnmount
三个函数的组合。