React-生命周期-其它方法
  TEZNKK3IfmPf 2023年11月13日 47 0

打开之前 React 的生命周期文档网页,点击展开不常用的生命周期如下:

React-生命周期-其它方法

  • getDerivedStateFromProps 函数:组件在被挂载或者更新时 (映射数据),就会回调
  • shouldComponentUpdate 函数:组件在更新时,决定是否要更新UI,就会回调
  • getSnapshotBeforeUpdate 函数:组件在更新时,最后能获取到更新之前数据的地方,就会回调

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={'BNTang'}/>
</div>
);
}
}

export default App;

React-生命周期-其它方法

getDerivedStateFromProps 只需要 ​​了解​​ 即可(用得非常非常的少)

更新时决定是否要更新 UI

返回值为布尔类型,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={'BNTang'}/>
</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={'BNTang'}/>
</div>
);
}
}

export default App;

React-生命周期-其它方法

注意点,getSnapshotBeforeUpdate 必须与 componentDidUpdate 一起使用。

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2023年11月15日   33   0   0 reactjavascript
  TEZNKK3IfmPf   2023年11月14日   23   0   0 react
  TEZNKK3IfmPf   2023年11月14日   17   0   0 react函数
  TEZNKK3IfmPf   2023年11月14日   29   0   0 react
  TEZNKK3IfmPf   2023年11月14日   29   0   0 react继承
  TEZNKK3IfmPf   2023年11月14日   38   0   0 react
  TEZNKK3IfmPf   2024年03月22日   71   0   0 htmlreact
  TEZNKK3IfmPf   2023年11月15日   36   0   0 react
  TEZNKK3IfmPf   2023年11月14日   34   0   0 react
TEZNKK3IfmPf