我正在学习reactjs,我看到很多人写,例如
class Trees extends Component {
render() {
const { plantTrees } = this.props;
return( ...
我想知道为什么要使用const {} = this.props
?使用它有什么好处吗?在渲染函数中初始化 const 变量的目的是什么?
实际上,这不仅适用于 React,而且它是 JavaScript 的 ES6 功能,称为解构赋值,它是从对象或数组中检索值的更好方法。在您的示例中,如果没有 ES6,我们必须使用
const plantTrees = this.props.plantTrees;
但是对于ES6,我们只需使用
const { plantTrees } = this.props
在数组的情况下,我们可以使用它
const [,price] = ['car',10000]
检索数组上的第二个元素并将其存储在名为 price 的常量上。
更多信息在这里: https://javascript.info/destructuring-assignment