簡體   English   中英

對Eslint進行銷毀分配

[英]React Eslint destructuring-assignment

我正在使用eslint規則react/destructuring-assignment 我該如何破壞它?

getStuff(model = this.state.model) {
   // some stuff
}

ESLINT不允許使用this.state.model ,它建議您利用解構:

const { model: stateModel } = this.state
getStuff(model = stateModel) {

但是,我擔心它是在React類組件內部。 因此,您不能在方法定義之前定義const或var。 您應該禁用該行的eslint:

getStuff(model = this.state.model) { // eslint-disable-line

或者,您可以這樣使用:

 getStuff(model) {
   const { model: stateModel } = this.state
   const passedModel = model ? model : stateModel

   // then work through passedModel
}

嗯,我可以想到這應該可以解決問題:

getStuff({state: {model}} = this) {

但是,坦率地說,我從未使用過這種方法。 請嘗試讓我知道。

更新

您也可以這樣使用:

getStuff(model) {
  const { model: stateModel } = this.state || { model: model }
  console.log(stateModel)

或者,簡單地:

getStuff(model) {
  const { model } = this.state || { model }
  // ----------------- similar to { model: model }
  console.log(model)

據我了解您的需求,您想要一個來自狀態的模型的默認變量,並在需要時也可以傳遞它。

getStuff(passedModel) {
   const { model } = this.state
   const toUseModelInMethod = passedModel || model
   // or 
   const toUseModelInMethod = passedModel ? passedModel : model
}

如果您只想從this.state獲取模型,那很簡單

getStuff() {
   const { model } - this.state
}

您也可以將狀態傳遞給方法

getStuff({ model }) {...}
this.getStuff(this.state) // linter is not happy
// that's is better
getStuff(model){...}
const { model } = this.state
this.getStuff(model)

您的例子不是破壞性的。 函數看起來像這樣:

function getStuff({ property1, property2 }) {
...
}

上面的示例將從任何傳遞給給定函數的對象中提取property1和property2。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM