简体   繁体   English

在React组件中进行销毁

[英]Destructuring in React components

There are a few articles stating that's best practice to use ES6 destructuring for React props & state. 有几篇文章指出将ES6分解用于React道具和状态的最佳实践。

Eg: const { showModal, hideModal } = this.props; 例如: const { showModal, hideModal } = this.props;

While I agree with this from the perspective of having much cleaner code, I had a discussion with one other developer suggesting that this should be done for class methods as well because it will bring a performance improvement. 尽管我从拥有更清晰的代码的角度同意了这一点,但我与另一位开发人员进行了讨论,建议对于类方法也应这样做,因为这会带来性能上的改进。

I say it won't be any faster and also it will make the code more confusing. 我说这不会更快,而且还会使代码更加混乱。

Does anyone have any opinion on this? 有人对此有意见吗?

First it will not make your code any slower/faster. 首先,它不会使您的代码变慢/变快。 I am sure someone might come out with some crazy synthetic case that will show 10ms improvement over the set with 10000000 records with 1000 properties each, but - in real world applications readability and maintainability is way more important. 我确信有人会提出一些疯狂的综合案例,该案例将比具有10000000条记录(每条记录具有1000个属性)的记录集表现出10ms的改进,但是-在现实世界中,应用程序的可读性和可维护性更为重要。 And if your code is smaller and easier to read and understand - it will contain less mistakes and as the end result will be quicker. 而且,如果您的代码更小并且更易于阅读和理解,那么它将包含更少的错误,并且最终结果会更快。

My personal opinion on destructuring is that I does lead us to writing less code that is easier to read, both for variables and parameters. 我对销毁的个人看法是,我确实带领我们编写了更少的变量和参数均易于阅读的代码。 Lets take this code from react-virtualized for example: 让我们从react-virtualized中获取以下代码:

_cellRenderer ({ columnIndex, key, rowIndex, style }) {
  if (columnIndex === 0) {
    return this._renderLeftSideCell({ columnIndex, key, rowIndex, style })
  } else {
    return this._renderBodyCell({ columnIndex, key, rowIndex, style })
  }
}

Here just by looking at the method declaration it is immediately obvious what parameters are. 在这里,仅通过查看方法声明,就可以明显看出参数是什么。

And now - compare it with this: 现在-将其与此:

_cellRenderer (p) {
  if (p.columnIndex === 0) {
    return this._renderLeftSideCell({ columnIndex: p.columnIndex, key: p.key, rowIndex: p.rowIndex, style: p.style })
  } else {
    return this._renderBodyCell({ columnIndex: p.columnIndex, key: p.key, rowIndex: p.rowIndex, style: p.style })
  }
}

Way more code and not so clean and easy to read, isn't it? 是不是更多的代码又不是那么干净易读,不是吗?

Yes, I agree with react-virtualised example as well. 是的,我也同意虚拟化示例。

But what about having here something like this? 但是在这里有这样的东西呢?

const { _renderBodyCell, _renderLeftSideCell } = this;

_cellRenderer ({ columnIndex, key, rowIndex, style }) {
  if (columnIndex === 0) {
    return _renderLeftSideCell({ columnIndex, key, rowIndex, style })
  } else {
    return _renderBodyCell({ columnIndex, key, rowIndex, style })
  }
}

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

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