You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

80 lines
2.4 KiB

import React from 'react'
class Test extends React.Component {
// 如果数据是组件的状态需要去影响视图,数据定义到 state 中
// 而如果数据不和视图绑定,那就定义一个普通的实例属性
// state 中尽量保持精简
// 设置一个定时器
timer = null // 实例属性
componentDidMount () {
this.timer = setInterval (() => {
console.log('定时器开启')
}, 1000)
}
// 组件的卸载阶段
// componentWillUnmount 是组件卸载,作用:执行清理工作(比如:清理定时器)
componentWillUnmount () {
console.log('componentWillUnmount')
// 清理定时器
clearInterval(this.timer)
}
render () {
return (
<div>this is Test</div>
)
}
}
class App extends React.Component {
// constructor 是创建组件时,最先执行,初始化的时候只执行一次
// 作用:1.初始化 state 2.创建 ref 3.使用 bind 解决 this 指向问题等
constructor () {
super()
console.log('constructor')
}
state = {
count: 0,
flag: true
}
clickHandler = () => {
this.setState ({
count: this.state.count + 1,
flag: !this.state.flag
})
}
// componentDidMount 是组件挂载(渲染 DOM 渲染)后执行,初始化的时候执行一次 (类似 vue 中的 mounted)
// 作用:1.发送网络请求 2.DOM 操作
componentDidMount () {
console.log('componentDidMount')
}
// 组件的更新阶段
// componentDidUpdate 是组件更新后(DOM 渲染完毕)
// 作用:DOM 操作,可以获取到更新后的 DOM 内容,不要直接调用 setState
componentDidUpdate() {
console.log('componentDidUpdate')
}
// render 是每次组件渲染都会触发
// 作用:渲染 UI (注意,不能在里面调用 setState() )
render () {
console.log('render')
return (
<div>
this is div
<button onClick={this.clickHandler}>{this.state.count}</button>
{/* 通过一个数据状态的切换,让 Test 组件进行销毁重建,就会发生组件卸载 */}
{this.state.flag ? <Test/> : null}
</div>
)
}
}
export default App