繁体   English   中英

如何动态更改函数的名称

[英]How to dynamically change a function's name

在调用我的 api 之前,我有一个 function 作为焦点。

我想通过简化我的 if 语句来减少臃肿。

目前我有一份声明清单。 其中2个如下所示

    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')
      })
    }

我想通过提出我的 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')
    })

我以前从来没有重命名过 function,所以我不确定如何开始。

我已经尝试过这样的事情,但它显然是行不通的。

   if(this.props.source === 1){
      const dataSource = 01
    }
   api.updateData + datasource + (.....

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

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

api[`updateData0${this.props.source}`]().then(/*...*/)

@Dupocas 方法可能是我使用 go 的方法。 也就是说,也可以使用数组来完成此操作:

// your updateData prop would look something like this:
// this.props.arrFn = [() => console.log('1'), () => console.log('2')]

const fireByDataSource = (source) => this.props.arrFn[source - 1](id, data)

componentDidMount() {
    if(this.props.source) return fireByDataSource(this.props.source)

    api.updateData01(id, data).then(res => {
      this.hideModal()
      fireByDataSource(1)
      console.log('DATA UPDATED')
    })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM