生命周期

componentWillMount 组件渲染前置性 componnetDidMount 组件渲染后执行

shouldComponentUpdate 返回true或false , true代表允许改变,false代表不允许改变

componentWillUpdate 数据在改变之前执行 (state, props)

componentDidUpdate 数据改变后执行

componentWillReveiceProps props 发生改变时执行

componentWillUnmount 组件卸载前执行

  1. import React from 'react'
  2. /**
  3. *
  4. * 先初始化props
  5. 在设置state
  6. 7个生命周期
  7. */
  8. export default class ComponentList extends React.Component {
  9. constructor(props) {
  10. super(props)
  11. this.state = {
  12. count: 0
  13. }
  14. }
  15. componentWillMount () {
  16. console.log('componnetWillMount')
  17. }
  18. componentDidMount () {
  19. console.log('componentDidMount')
  20. }
  21. shouldComponentUpdate () {
  22. return true
  23. }
  24. componentWillUpdate () {
  25. console.log('componnetWillUpdate')
  26. }
  27. componentDidUpdate () {
  28. console.log('componentDidUpdate')
  29. }
  30. componentWillReceiveProps () {
  31. // 父子交互
  32. console.log('componentWillReceiveProps')
  33. }
  34. componentWillUnmount () {
  35. console.log('componentWillUnmount')
  36. }
  37. increase = () => {
  38. // 执行shouldComponentUpdate componentWillUpdate componnetDidUpdate
  39. this.setState({
  40. count: this.state.count += 1
  41. })
  42. }
  43. clickChange = () => {
  44. this.props.handleParent('接收到了儿子触sdf发')
  45. }
  46. render() {
  47. const { count } = this.state
  48. return (
  49. <div>
  50. <h3>
  51. 生命周期函数 { count } { this.props.title }
  52. </h3>
  53. <button onClick={ this.increase }>增加</button>
  54. <button onClick={ this.clickChange }>触发父方法</button>
  55. </div>
  56. )
  57. }
  58. }
  • 父元素

    handleP 是子 触发 父方法, 可以传参, 父元素需要传递方法给子组件

  1. handleP = (data) => {
  2. console.log(data)
  3. }
  4. <ComponentLife handleParent={ this.handleP } title={ this.state.title }/>