react中getDerivedStateFromProps和componentDidUpdate配合使用

React 父组件通过props控制子组件执行不同的方法进行渲染

import React, { Component } from 'react';

class Item extends Component {
  constructor(props) {
    super(props)
    this.state = {
      content: '',
      fun1: 0,
      fun2: 0,
      runFun: 'fun1',
      shouldUpdateByFun1: false,
      shouldUpdateByFun2: false,
      myArgument: []
    }
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.fun1 !== prevState.fun1) {
      return {
        fun1: nextProps.fun1,
        runFun: 'fun1',
        shouldUpdateByFun1: true,
        myArgument: nextProps.myArgument 
      }
    } else if (nextProps.fun2 !== prevState.fun2) {
      return {
        fun2: nextProps.fun2,
        runFun: 'fun2',
        shouldUpdateByFun2: true,
        myArgument: nextProps.myArgument 
      }
    }
    return null
  }

  componentDidUpdate() {
    let { runFun, myArgument, shouldUpdateByFun1, shouldUpdateByFun2 } = this.state

    if (runFun === 'fun1' && shouldUpdateByFun1) {
      this.fun1(myArgument)
    } else if (runFun === 'fun2' && shouldUpdateByFun2) {
      this.fun2(myArgument)
    }
  }

  //函数里可以包含ajax请求等复杂的逻辑
  fun1(myArgument) {
    let { fun1 } = this.props
    setTimeout(() => {
      this.setState({
        content: 'from fun1:' + myArgument,
        shouldUpdateByFun1: false
      })
    }, 1000)

    console.log('fun1执行次数:' + fun1)
  }
  fun2(myArgument) {
    let { fun2 } = this.props
    setTimeout(() => {
      this.setState({
        content: 'from fun2:' + myArgument,
        shouldUpdateByFun2: false
      })
    }, 1000)    
    console.log('fun2执行次数:' + fun2)
  }
  render() {
    let { content } = this.state
    return (
      <div>
        {content}
      </div>
    )
  }
}

//父组件通过props控制子组件执行不同的方法进行渲染
class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      fun1: 0,
      fun2: 0,
      myArgument: []
    }
  }
  render() {
    let { fun1, fun2, myArgument } = this.state
    return (
      <div>
        <Item fun1={fun1} fun2={fun2} myArgument={myArgument}/>
        <button onClick={this.handleFun1.bind(this)}>Fun1</button>
        <button onClick={this.handleFun2.bind(this)}>Fun2</button>
      </div>
    );
  }
}

//事件
Object.assign(App.prototype, {
  handleFun1() {
    let { fun1 } = this.state
    fun1 = fun1 + 1
    this.setState({
      fun1,
      myArgument: ['xu', 'tongbao']
    })
  },
  handleFun2() {
    let { fun2 } = this.state
    fun2 = fun2 + 1
    this.setState({
      fun2,
      myArgument: ['徐', '同保']
    })
  }
})

export default App
原文地址:https://www.cnblogs.com/xutongbao/p/11915699.html