代码之家  ›  专栏  ›  技术社区  ›  ATOzTOA

React-Eslint解构赋值

  •  1
  • ATOzTOA  · 技术社区  · 7 年前

    我正在使用eslint规则 react/destructuring-assignment

    getStuff(model = this.state.model) {
       // some stuff
    }
    
    3 回复  |  直到 7 年前
        1
  •  3
  •   Bhojendra Rauniyar    7 年前

    ESLINT不允许使用 this.state.model 它建议您利用分解:

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

    但是,恐怕是在react类组件中。因此,您不能在方法定义之前定义常量或变量。您应该禁用该行的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)
    
        2
  •  1
  •   victor zadorozhnyy    7 年前

    正如我理解您的需要,您希望为来自state的模型提供一个默认var,并且如果需要,还可以传递它。

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

    如果你只是想从这里得到模型,说明它很简单

    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)
    
        3
  •  0
  •   Keith Rousseau    7 年前

    你的例子不是在分解结构。函数如下所示:

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