美文网首页
React.Component、React.PureCompon

React.Component、React.PureCompon

作者: 年轻人多学点 | 来源:发表于2022-09-02 10:31 被阅读0次
  1. React.Component
    最常见的,包含最常用的render(),componentDidMount(),shouldComponentUpdate…
    shouldComponentUpdate(nextProps, nextState)
    判断 React 组件的输出是否受当前 state 或 props 更改的影响。意思就是只要组件的 props 或者 state 发生了变化,就会重新构建 virtual DOM,然后使用 diff算法进行比较,再接着根据比较结果决定是否重新渲染整个组件。shouldComponentUpdate函数是重渲染时render()函数调用前被调用的函数,它接受两个参数:nextProps和nextState,分别表示下一个props和下一个state的值。并且,当函数返回false时候,阻止接下来的render()函数的调用,阻止组件重渲染,而返回true时,组件照常重渲染。
    React.Component 并未实现 shouldComponentUpdate(),如何利用shouldComponentUpdate钩子函数优化react性能
    demo1.tsx
import React, { PureComponent,Component } from 'react';
class CompareComponent extends Component<any, any>{
 state = {
   isShow: false,
   count:1
 }
 shouldComponentUpdate(nextProps, nextState){
   if(nextState.isShow===this.state.isShow){
     return false // false则不会调用render
   }
   return true
 }
 changeState = () => {
   this.setState({
     isShow: true
   })
 };

 handleAdd=()=>{
   const {count} = this.state
   this.setState({
     count:count+1
   })
 }

 render() {
   console.log('render');
   return (
     <div>
       <button onClick={this.changeState}>点击赋值</button>
       <div>{this.state.isShow.toString()}</div>

       <button onClick={this.handleAdd}>点击{this.state.count}</button>
     </div>
   );
 }
}
export default CompareComponent

2.React.PureComponent
React.PureComponent 与 React.Component 几乎完全相同,也包括render,生命周期等等。但 React.PureComponent 通过props和state的浅对比来实现 shouldComponentUpate()。如果对象包含复杂的数据结构,它可能会因深层的数据不一致而产生错误的否定判断(表现为对象深层的数据已改变视图却没有更新

React.PureComponent在某些条件下,render不用重新渲染
PureComponent中不能有shouldComponentUpdate
demo2.tsx

import React, { PureComponent,Component } from 'react';

class CompareComponent extends PureComponent{
  state = {
    isShow: false,
    count:1
  }
  changeState = () => {
    this.setState({
      isShow: true
    })
  };
  handleAdd=()=>{
    const {count} = this.state
    this.setState({
      count:count+1
    })
  }
  render() {
    console.log('render');
    return (
      <div>
        <button onClick={this.changeState}>点击赋值</button>
        <div>{this.state.isShow.toString()}</div>

        <button onClick={this.handleAdd}>点击{this.state.count}</button>
      </div>
    );
  }
}
export default CompareComponent

3.React.Component、React.PureComponent的区别
通过查看render的渲染次数会发现规律
shouldComponentUpdate返回true的话,React.Component无论state发生新的改变,都会重新渲染render。若是返回false,则state在满足条件下返回false的话,不会重新渲染render

PureComponent = shouldComponentUpdate(false) + React.Component
4.React.FC
React.FC<>的在typescript使用的一个泛型,这个泛型里面可以使用useState
这个里面无生命周期。
通过useState可以实现在函数组件中实现值的更新
useState在前两者中不能使用,只能在函数组件或者泛型里面使用。具体如何使用,可参考我这篇文章

import React, { useState } from 'react';

export interface NoticeProps {
  name: string;
  address: string
}

const Notice: React.FC<NoticeProps> = (props) => {
  const [ name, setName ] = useState('angle');
  const [ count, setCount ] = useState(1);
  const addCount=()=>{
    setCount(count+1)
  }

  console.log(count)
  return <div>
    <p>我是message页面,name是:{name}</p>
    <p>我是message页面,count是:{count}</p>
    <button onClick={() => setName('jane')}>点击我改变name</button>
    <br />
    <button onClick={addCount}>点击我改变count</button>
  </div>;
}
export default Notice;


一、React.FC<>
1.React.FC是函数式组件,是在TypeScript使用的一个泛型,FC就是FunctionComponent的缩写,事实上React.FC可以写成React.FunctionComponent:

const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
  <div>{message}</div>
);

2.React.FC 包含了 PropsWithChildren 的泛型,不用显式的声明 props.children 的类型。React.FC<> 对于返回类型是显式的,而普通函数版本是隐式的(否则需要附加注释)。

3.React.FC提供了类型检查和自动完成的静态属性:displayName,propTypes和defaultProps(注意:defaultProps与React.FC结合使用会存在一些问题)。

4.我们使用React.FC来写 React 组件的时候,是不能用setState的,取而代之的是useState()、useEffect等 Hook API。

const SampleModel: React.FC<{}> = () =>{   //React.FC<>为typescript使用的泛型
    const [createModalVisible, handleModalVisible] = useState<boolean>(false); 
    return{
    {/** 触发模态框**/}
    <Button style={{fontSize:'25px'}}  onClick={()=>handleModalVisible(true)} >样例</Button>
    {/** 模态框组件**/}
    <Model onCancel={() => handleModalVisible(false)} ModalVisible={createModalVisible} /> 
  }

二、class xx extends React.Component
如需定义 class 组件,需要继承 React.Component。React.Component是类组件,在TypeScript中,React.Component是通用类型(aka React.Component<PropType, StateType>),因此要为其提供(可选)prop和state类型参数:

例子(这里使用阿里的Ant Desgin Pro框架来演示)::

class SampleModel extends React.Component {
  state = {
    createModalVisible:false,
  };

  handleModalVisible =(cVisible:boolean)=>{
    this.setState({createModalVisible:cVisible});
  };
  return {
  {/** 触发模态框**/}
    <Button onClick={()=>this.handleModalVisible(true)} >样例</Button>
    {/** 模态框组件**/}
    <Model onCancel={() => handleModalVisible(false)} ModalVisible={this.state.createModalVisible} /> 
  }

ps:简单来说,不知道用什么组件类型时,就用 React.FC。


React的组件可定义为函数(React.FC<>)或class(继承React.Componnent)的形式

React.FC<>

1.React.FC是函数式组件 是在TypeScript使用的一个泛型,FC就是FunctionComponent的缩写 事实上React.FC可以写成React.FunctionComponent

const App:React.FunctionComponent<{message:string}>=({message})=>(
    <div>{message}</div>
)

2.React.FC包含了PropsWithChildren的泛型,不用显示的声明props.children的类型。React.FC<>对于返回类型是显式的 而普通函数版本是隐式的(否则需要添加注释)

  1. React.FC提供了类型检查和自动完成的静态属性:displayName,propTypes和defaultProps(注意defaultProps与React.FC结合使用会存在一些问题)

  2. 我们使用React.FC来写React组件的时候 是不能用setState的 取而代之的是useState()、useEffect等Hook API

例子(这里使用阿里的Ant Design Pro框架来演示):

const SampleModel: React.FC<{}> = ()=>{ //React.FC<> 为typeScript使用的泛型
   const  [createModalVisiable,handleModelVisiable] = useState<boolean>(false)
   return {
        //触发模态框
        <Button style={{fontSize:'25px'}} onClick={()=>handleModalVisiable(true)}>样例<Button/>
        //模态块组件
        <Model onCancel={()=>handleModelVisiible(false)} ModelVisiable={createVisiable}/>
   }
}

class xx extends React.Component

如需定义class组件 需继承React.Component。React.Component是类组件 在typescript中 React.Component是通用类型(aka React.Component<PropType,stateType>),因此要為其提供(可选)prop和state类型参数:
例子(Ant Design Pro框架来演示):

class SampleModel extends React.Component{
    state = {
       createModelVisiable:false
}
    handleModelVisiable = (cVisiable:boolean)=>{
    this.setState({createModelVisiable:cVisiable})
}
return {
//触发模态框
<Button onClick={()=>this.handleModelVisiable(true)}>样例</Button>
//模态框组件
<Model onCancel={()=>handleVisiable(false)} ModelVisiable={this.state.createModelVisiable}/>
}
}

相关文章

网友评论

      本文标题:React.Component、React.PureCompon

      本文链接:https://www.haomeiwen.com/subject/atbenrtx.html