cass 组件
- class组件通常拥有状态和生命周期,继承于Component,实现render方法
import React, { Component } from 'react'
export default class ClassComponent extends Component {
constructor(props) {
super(props)
this.state = {
data: new Date()
}
}
componentDidMount() {
this.time = setInterval(() => {
this.setState({
data: new Date()
})
}, 1000);
}
componentWillUnmount() {
clearInterval(this.time)
}
render() {
const { data } = this.state;
return (
<div>
{data.toLocaleTimeString()}
</div>
)
}
}
function组件
import React, { useState, useEffect } from 'react'
function FunctionComponent() {
const [date, setDate] = useState(new Date());
useEffect(() => {
// 默认执行一次,第二个参数数据中的数据发生变化也会执行
const timer = setInterval(() => {
setDate(new Date())
}, 1000);
return () => clearInterval(timer) // 组件卸载时执行
}, []) // 副作用光联得数据,为空则不关联数据
return (
<div>
{date.toLocaleTimeString()}
</div>
)
}
export default FunctionComponent;
-
useEffect
相当于componentDidMount,componentWillUnmount,componentDidUpdate,三个生命周期的组合
网友评论