How to dynamically change a function's name

Nei*_*eil 4 javascript reactjs

I have a function which acts as a sort of focal point before calling my api.

I want to reduce the bloat a little by simplifying my if statements.

Currently I have a list of statements. 2 of which are shown below

    if (this.props.source === 1) {
      api.updateData01(id, data).then(res => {
        this.hideModal()
        this.props.updateData01()
        console.log('DATA UPDATED')
      })
    }
    if (this.props.source === 2) {
      api.updateData02(id, data).then(res => {
        this.hideModal()
        this.props.updateData02()
        console.log('DATA UPDATED')
      })
    }
Run Code Online (Sandbox Code Playgroud)

我想通过调出if语句来简化它,而是动态地重命名这些函数。

遵循以下原则

    if(this.props.source === 1){
      //rename updateData to updateData01
    }
    if(this.props.source === 2){
      //rename updateData to updateData02
    }

    api.updateData01(id, data).then(res => {
      this.hideModal()
      this.props.updateData01()
      console.log('DATA UPDATED')
    })
Run Code Online (Sandbox Code Playgroud)

在此之前,我从来不需要重命名函数,所以不确定如何开始。

我已经尝试过类似的操作,但显然无法正常工作。

   if(this.props.source === 1){
      const dataSource = 01
    }
   api.updateData + datasource + (.....
Run Code Online (Sandbox Code Playgroud)

Dup*_*cas 11

您可以使用动态属性名称来基于哈希(api)来访问正确的函数,而不必重命名函数

const api = {
    updateData01 : () =>{},
    updateData02 : () =>{},
    /*...*/
    updateData0N : () =>{}
}

api[`updateData0${this.props.source}`]().then(/*...*/)
Run Code Online (Sandbox Code Playgroud)