才知道,从阵营v15.3.0,我们有一个新的名为基类PureComponent与扩展PureRenderMixin内置.我所理解的是,在引擎盖下,它采用了内部道具的浅层比较shouldComponentUpdate.
现在我们有3种方法来定义React组件:
PureComponent类的组件Component类的普通组件一段时间后,我们习惯将无状态组件称为纯组件,甚至是哑组件.似乎"纯"这个词的整个定义现在在React中已经改变了.
虽然我理解这三者之间的基本差异,但我仍然不确定何时选择什么.还有什么是性能影响和权衡取舍?
这些是我希望澄清的问题:
PureComponent类(为了性能)?Component当我总能使用PureComponent以获得更好的性能时,我是否需要扩展普通类?我的代码有一个组件,它接受两个 props 并拥有自己的内部状态。
仅当组件的 props 更改时,组件才应重新渲染。状态更改不应触发重新渲染。
此行为可以使用基于类的组件和自定义shouldComponentUpdate函数来实现。
然而,这将是代码库中第一个基于类的组件。一切都是通过功能组件和钩子完成的。因此我想知道是否可以使用功能组件来编写所需的功能。
在一些没有解决实际问题的答案之后,我想我必须重新表述我的问题。这是一个包含两个组件的最小示例:
为了演示所需的功能,我使用基于类的组件实现了 Inner。该代码的实时版本可以在codesandbox 上找到。如何将其迁移到功能组件:
Inner.tsx:
import React, { Component } from 'react'
interface InnerProps{outerNum:number}
interface InnerState{innerNum:number}
export default class Inner extends Component<InnerProps, InnerState> {
state = {innerNum:0};
shouldComponentUpdate(nextProps:InnerProps, nextState:InnerState){
return this.props != nextProps;
}
render() {
return (
<button onClick={()=>{
this.setState({innerNum: Math.floor(Math.random()*10)})
}}>
{`${this.props.outerNum}, ${this.state.innerNum}`}
</button>
)
}
}
Run Code Online (Sandbox Code Playgroud)
外部.tsx:
import React, { useState } from "react";
import Inner from …Run Code Online (Sandbox Code Playgroud)