componentWillMount:组件挂载之前执行,只执行一次
componentDidMount: 组件渲染完成,只执行一次
=======================================================
componentWillRecevieProps: 组件将要接收新的props执行
shouldComponentUpdate: 判断组件是否应该重新渲染,默认是true
componentWillUpdate: 组件将要重新渲染
componentDidUpdate: 组件重新渲染完成
=======================================================
componentWillUnmount: 卸载组件
定制组件的shouldComponentUpdate钩⼦
通过shouldComponentUpdate优化组件
// 简单例子
shouldComponentUpdate(nextProps) {
if(JSON.stringify(nextProps) == JSON.stringify(this.props)) {
return false
}else {
return true
}
}
import React, {Component} from "react";
export default class CommentList extends Component {
constructor(props) {
super(props);
this.state = {comments: []};
}
componentDidMount() {
setInterval(() => {
this.setState({
comments: [
{
author: "⼩明",
body: "这是⼩明写的⽂章",
},
{
author: "⼩红",
body: "这是⼩红写的⽂章",
},
],
});
}, 1000);
}
render() {
const {comments} = this.state;
return (
<div>
<h1>CommentList</h1>
{comments.map((c, i) => {
return <Comment key={i} data={c}/>;
})}
</div>
);
}
}
class Comment extends Component {
shouldComponentUpdate(nextProps, nextState) {
const {author, body} = nextProps.data;
const {author: nowAuthor, body: nowBody} = this.props.data;
if (body === nowBody && author === nowAuthor) {
return false; //如果不执⾏这⾥,将会多次render
}
return true;
}
render() {
console.log("hah");
const {body, author} = this.props.data;
return (
<div>
<p>作者: {author}</p>
<p>正⽂:{body}</p>
<p>---------------------------------</p>
</div>
);
}
}
PureComponent
定制了shouldComponentUpdate后的Component
缺点是必须要⽤class形式,⽽且要注意是浅⽐较
import React, {Component, PureComponent} from "react";
export default class PuerComponentPage extends PureComponent {
constructor(props) {
super(props);
this.state = {
counter: 0,
obj: {
num: 100,
},
};
}
setCounter = () => {
this.setState({
counter: 1,
obj: {
num: 200,
},
});
console.log("setCounter");
};
render() {
console.log("render");
const {counter, obj} = this.state;
return (
<div>
<button onClick={this.setCounter}>setCounter</button>
<div>counter: {counter}</div>
<div>obj.num: {obj.num}</div>
</div>
);
}
}
React.memo
React.memo(…) 是React v16.6引进来的新属性。它的作⽤和 React.PureComponent 类似,是⽤来控制函数组件的重新渲染的。
React.memo(…) 其实就是函数组件的 React.PureComponent 。
缺点和PureComponent一样 要注意是浅⽐较
export default class MemoPage extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
obj: {num: -1},
};
}
setCounter = () => {
this.setState({
counter: 1,
// obj: {
// num: 100,
// },
});
};
render() {
const {counter} = this.state;
return (
<div>
<h1>MemoPage</h1>
<button onClick={this.setCounter}>按钮</button>
{/* <PuerCounter counter={counter} obj={obj} /> */}
<PuerCounter counter={counter}/>
</div>
);
}
}
const PuerCounter = memo(props => {
console.log("render");
return <div>{props.counter}</div>;
});