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

2 years ago
  1. import React from 'react'
  2. class Test extends React.Component {
  3. // 如果数据是组件的状态需要去影响视图,数据定义到 state 中
  4. // 而如果数据不和视图绑定,那就定义一个普通的实例属性
  5. // state 中尽量保持精简
  6. // 设置一个定时器
  7. timer = null // 实例属性
  8. componentDidMount () {
  9. this.timer = setInterval (() => {
  10. console.log('定时器开启')
  11. }, 1000)
  12. }
  13. // 组件的卸载阶段
  14. // componentWillUnmount 是组件卸载,作用:执行清理工作(比如:清理定时器)
  15. componentWillUnmount () {
  16. console.log('componentWillUnmount')
  17. // 清理定时器
  18. clearInterval(this.timer)
  19. }
  20. render () {
  21. return (
  22. <div>this is Test</div>
  23. )
  24. }
  25. }
  26. class App extends React.Component {
  27. // constructor 是创建组件时,最先执行,初始化的时候只执行一次
  28. // 作用:1.初始化 state 2.创建 ref 3.使用 bind 解决 this 指向问题等
  29. constructor () {
  30. super()
  31. console.log('constructor')
  32. }
  33. state = {
  34. count: 0,
  35. flag: true
  36. }
  37. clickHandler = () => {
  38. this.setState ({
  39. count: this.state.count + 1,
  40. flag: !this.state.flag
  41. })
  42. }
  43. // componentDidMount 是组件挂载(渲染 DOM 渲染)后执行,初始化的时候执行一次 (类似 vue 中的 mounted)
  44. // 作用:1.发送网络请求 2.DOM 操作
  45. componentDidMount () {
  46. console.log('componentDidMount')
  47. }
  48. // 组件的更新阶段
  49. // componentDidUpdate 是组件更新后(DOM 渲染完毕)
  50. // 作用:DOM 操作,可以获取到更新后的 DOM 内容,不要直接调用 setState
  51. componentDidUpdate() {
  52. console.log('componentDidUpdate')
  53. }
  54. // render 是每次组件渲染都会触发
  55. // 作用:渲染 UI (注意,不能在里面调用 setState() )
  56. render () {
  57. console.log('render')
  58. return (
  59. <div>
  60. this is div
  61. <button onClick={this.clickHandler}>{this.state.count}</button>
  62. {/* 通过一个数据状态的切换,让 Test 组件进行销毁重建,就会发生组件卸载 */}
  63. {this.state.flag ? <Test/> : null}
  64. </div>
  65. )
  66. }
  67. }
  68. export default App