簡體   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