无状态组件
函数,有两个参数props和context,没有内部状态state,无生命周期,没有实例化过程,也就没有ref,没有this。
专注于UI层,它自身不会对业务逻辑进行处理,它自身的一切只与props相关,一切需要定义state的地方,你都应该抽离到容器组件上面,或者使用redux之类的东西,进行抽离。
缺点:每次props
更新,它都会重新绘制render
函数。
function Animal(props, context) {
return(
<div>
<label></label>
<Input />
</div>
)
}
高阶组件
高阶组件的本质,是一个函数,只不过这个函数的返回值,是一个class类型的组件。
function highComponent(MyComponent) {
return class A extends Component {
constructor(props) {
super(props);
this.state = {
isShow: true
}
}
componentDidMount() {
this.setState({
isShow: false,
})
}
render() {
return (
<MyComponent isShow={this.state.isShow}></MyComponent>
)
}
}
}
高阶组件聚焦于业务层,不关心组件的UI层,所以在上面的示例中,我们可以把MyComponent这个传递进来的组件,写成无状态组件。
纯组件
PureComponent 内实现了shouldComponentUpdate(),它会自动检查组件是否需要重新渲染。
props或setState使state改变了(浅比较)组件就更新,只比较props
和state
的内存地址,如果内存地址相同,则不更新。
通过减少render调用次数,来减少性能损耗。
使用场景应该是局部数据发生改变的场景,比如带有输入框、switch
开关等的UI组件就可以使用PureComponent
组件封装。
class Cat extends React.Purecomponnet {
props 或state值的地址改变才走刷新
render(){
}
}