直接使用 this.props 或 this.state 与设置 const

Using this.props or this.state directly vs setting const

我是 React 新手,在查看示例时,我发现很多教程没有直接使用 this.propsthis.state。相反,他们会在函数的开头设置一个常量。我交替使用了这两者,没有发现任何功能差异。

使用 const 有什么好处吗?

即。

const {
    error
} = this.state;

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

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

这叫做Destructuring,ES6的一个特性。

功能上没有差异,但使用解构的好处很小。

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

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

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

你这样定义后

const {error} = this.state;

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