我正在学习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]
检索数组中的第二个元素并将其存储在名为价格的常量中。
关于Reactjs:为什么使用 const {} = this.props 以及为什么将其放在渲染函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51012674/