在react中,当父组件的state更新时,即使子组件的props没有更新,子组件也会触发render函数,这样就造成了性能的浪费。
解决办法:在子组件中使用shouldComponentUpdate生命周期函数来判断是否要触发render函数。
shouldComponentUpdate接收两个参数,一个是nextProps,代表更新前的props;一个是nextState,代表更新前的state。shouldComponentUpdate返回一个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> ) } }