React——基于类的组件优化

本文介绍了在React中,当父组件state更新时,即使子组件props未变也会导致子组件重新渲染,从而造成性能浪费的问题。为了解决这个问题,可以使用shouldComponentUpdate生命周期方法进行优化。在该方法中,通过比较nextProps和当前props,只有当props改变时才返回true,触发render。示例代码展示了如何实现这个功能,从而提高应用的性能。
摘要由CSDN通过智能技术生成

在react中,当父组件的state更新时,即使子组件的props没有更新,子组件也会触发render函数,这样就造成了性能的浪费。

  • 解决办法:

在子组件中使用shouldComponentUpdate生命周期函数来判断是否要触发render函数。

shouldComponentUpdate接收两个参数,一个是nextProps,代表更新前的props;一个是nextState,代表更新前的stateshouldComponentUpdate返回一个boolean值,为false时,不执行render函数;为true时,执行render函数。

所以我们可以根据nextProps参数对比当前组件内的props,如果发生变化,就返回true,否则便返回false

  • 示例代码如下:
import React, { Component } from "react";

interface IProps {
  content: string;
}
interface IState {}

export default class ExampleChild extends Component<IProps, IState> {
   /**
    * 组件优化
    * @param nextProps 更新前的props
    * @param nextState 更新前的state
    */
	shouldComponentUpdate(nextProps: IProps, nextState: IState): boolean {
	  if (nextProps.content !== this.props.content) {
	    return true;
	  }
	  return false;
	}
	
	constructor(props: IProps) {
	    super(props);
	    this.state = {};
	    this.deleteItem = this.deleteItem.bind(this);
	}
	  
	public render(){
		let {content} = this.props;
		return(
			<div>{content}</div>
		)
	}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱学习的前端小黄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值