【问题标题】:Using this.props or this.state directly vs setting const直接使用 this.props 或 this.state 与设置 const
【发布时间】:2019-11-09 18:34:49
【问题描述】:

我是新手,在查看示例时,我发现很多教程都没有直接使用 this.propsthis.state。相反,他们将在函数的开头设置一个 const。我已将两者互换使用,但没有发现任何功能差异。

使用const有什么好处吗?

即。

const {
    error
} = this.state;

{error && <p>{error.message}</p>}

{this.state.error && <p>{this.state.error.message}</p>}

【问题讨论】:

  • 没有功能上的区别,这是一个偏好问题(因此这里是基于意见的主题)。

标签: javascript reactjs constants react-props react-state


【解决方案1】:

这称为Destructuring,是 ES6 的一个特性。

在功能上没有区别,但使用解构几乎没有什么好处。

首先,更简洁的代码。如果您在代码块的顶部解构一个对象,读者会更清楚您将使用哪些变量。

其次,它将对象属性放在可以提高性能的局部变量中,尤其是当您像在循环中一样多次使用变量时。

【讨论】:

    【解决方案2】:

    正如您自己所说,根本没有区别,这是真的。我使用 const 的简单答案是

    在你这样定义之后

    const {error} = this.state;
    

    现在你可以在下面的代码中只使用术语(错误)而不是冗长的(this.state.error) 所以只是为了简单

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      • 2017-04-08
      • 2019-11-11
      • 2018-01-09
      • 2018-09-28
      • 1970-01-01
      相关资源
      最近更新 更多