React类组件中`const { props } = this`写法的含义与用途是什么?
const { props } = this 写法说明 - 这是ES6对象解构赋值的标准用法,完全等价于常规赋值逻辑
const props = this.props,没有特殊运行时行为。 - 因为示例中的
render是类属性形式的箭头函数,执行时this会自动绑定到当前组件类的实例,所以从this上解构出的props和直接通过this.props访问的对象是同一个引用,不存在值拷贝、没有额外性能开销。
实际作用
- 简化书写冗余:方法体内后续读取props属性时,不需要每次都重复写
this.前缀,直接使用解构得到的props变量即可。 - 提升代码可读性:把方法依赖的类实例属性在开头集中解构声明,能快速让阅读者识别该方法的依赖项,不需要在方法体各处零散查找对
this.xxx的引用。
两种写法的等价效果对照
// 无解构写法 render = () => { return ( <div> <h1>{this.props.pageTitle}</h1> <p>{this.props.content}</p> <button onClick={this.props.onConfirm}>确认</button> </div> ) } // 带解构写法 render = () => { const { props } = this return ( <div> <h1>{props.pageTitle}</h1> <p>{props.content}</p> <button onClick={props.onConfirm}>确认</button> </div> ) }
内容的提问来源于stack exchange,提问作者Arjunan Ranjit
相关产品推荐
相关产品推荐

