React的生命周期是组件在其生命周期内的一系列事件和方法调用,允许您管理组件的行为和状态。除了常见的生命周期方法如componentDidMount和componentDidUpdate之外,还有一些其他方法可供使用。
打开之前 React 的生命周期文档网页,点击展开不常用的生命周期如下:
App.js:
import React from 'react';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
}
}
static getDerivedStateFromProps(props, state) {
console.log('挂载或更新时-映射数据-getDerivedStateFromProps');
console.log(props, state);
return null;
}
render() {
return (
<div>
<p>Home</p>
<button onClick={() => {
this.btnClick();
}}>Home按钮
</button>
</div>
);
}
btnClick() {
this.setState({
count: 1
});
}
}
class App extends React.Component {
render() {
return (
<div>
<Home name={'yangbuyiya'}/>
</div>
);
}
}
export default App;
getDerivedStateFromProps 只需要 了解
即可(用得非常非常的少)
返回值为布尔类型,true 代表需要更新 UI,false 代表不需要更新 UI。
import React from 'react';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
}
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
console.log('更新时-决定是否要更新UI-shouldComponentUpdate');
return true;
}
render() {
console.log("渲染 UI");
return (
<div>
<p>Home</p>
<button onClick={() => {
this.btnClick();
}}>Home按钮
</button>
</div>
);
}
btnClick() {
this.setState({
count: 1
});
}
}
class App extends React.Component {
render() {
return (
<div>
<Home name={'yangbuyiya'}/>
</div>
);
}
}
export default App;
App.js:
import React from 'react';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
}
}
render() {
return (
<div>
<p>Home</p>
<button onClick={() => {
this.btnClick();
}}>Home按钮
</button>
</div>
);
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('更新时-最后能获取到更新之前数据的地方-getSnapshotBeforeUpdate');
console.log(prevProps, prevState);
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('更新时-componentDidUpdate');
}
btnClick() {
this.setState({
count: 1
});
}
}
class App extends React.Component {
render() {
return (
<div>
<Home name={'yangbuyiya'}/>
</div>
);
}
}
export default App;
注意点,getSnapshotBeforeUpdate 必须与 componentDidUpdate 一起使用。
本期结束咱们下次再见👋~
🌊 关注我不迷路,如果本篇文章对你有所帮助,或者你有什么疑问,欢迎在评论区留言,我一般看到都会回复的。大家点赞支持一下哟~ 💗
undefined(https://foruda.gitee.com/i
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。