使用 shouldComponentUpdate 方法控制子组件更新
示例代码:
class ParentComponent extends React.Component { constructor(props) { super(props); this.state = { data: "Hello World" }; }
shouldComponentUpdate(nextProps, nextState) { if (this.state.data !== nextState.data) { return false; } return true; }
render() { return (
class ChildComponent extends React.Component { constructor(props) { super(props); this.state = { message: "I am a child component." }; }
render() { return (
在父组件中定义 shouldComponentUpdate 方法,判断当前状态与下一状态是否有变化,如果没有变化,则返回 false ,子组件不会被更新。在子组件中写 render 方法,渲染当前组件。