9. 生命周期

This commit is contained in:
shikong 2024-10-26 23:28:42 +08:00
parent ec0298cf63
commit 8448575d8c
Signed by: Shikong
GPG Key ID: BD85FF18B373C341
3 changed files with 45 additions and 10 deletions

View File

@ -2,33 +2,61 @@ import React from "react";
import PropTypes from "proptypes"
// 模块化 css, 后缀 .module.css
import SonComponentCss from "./SonComponent.module.css"
export default class SonComponent extends React.PureComponent {
export default class SonComponent extends React.Component {
state = {
msg: "SonComponent Msg",
showChildrenBorder: true,
childrenClass: []
}
// constructor(props) {
// super(props);
// console.log(props)
// }
constructor(props) {
super(props);
console.log("[constructor] SonComponent")
}
// 相当于 vue mounted
componentDidMount() {
this.changeChildrenClass()
console.log('[挂载] SonComponent 组件后执行的操作');
}
// 优化生命周期
// 手动实现 类似 React.PureComponent 的功能
// 如果返回值为 false 则不会调用 render 更新组件
shouldComponentUpdate(nextProps, nextState, nextContext) {
console.log("[shouldComponentUpdate] SonComponent")
console.log("修改前 => ", this.state, "修改后 =>", nextState)
// 是否需要更新组件
// return !Object.keys(this.state).reduce((prev,key)=> {
// return prev?this.state[key] === nextState[key]:prev;
// }, true)
for(let key in this.state){
console.log(key, this.state[key], nextState[key], this.state[key] !== nextState[key])
if(this.state[key] !== nextState[key]){
return true;
}
}
return false;
}
// 相当于 vue updated
componentDidUpdate(prevProps, prevState, snapshot) {
// 当count更新时执行的操作
console.log('SonComponent 组件后更新,执行的操作:', this.state);
console.log('[componentDidUpdate] SonComponent 组件后更新,执行的操作:', this.state);
}
// 相当于 vue unmount
componentWillUnmount() {
console.log('[卸载] SonComponent 组件 前执行的操作');
}
static getDerivedStateFromProps(props, state){
console.log("[getDerivedStateFromProps] SonComponent", props, state)
return null
}
switchChildrenBorder = () => {
this.setState({
...this.state,
@ -51,6 +79,7 @@ export default class SonComponent extends React.PureComponent {
}
render() {
console.log("[render] SonComponent")
return <div style={{border: '1px solid', width: '80%', overflow: 'auto'}}>
子组件

View File

@ -35,9 +35,10 @@ export default function SonComponent2(props= {
}
function revokeChangeMsg(){
let count = state.count
setState({
...state,
// count: state.count > 0 ? --state.count : 0,
count: count > 0 ? --count : 0,
tmp: props.changeMsg(state.tmp)
})
}

View File

@ -6,9 +6,14 @@ import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
/**
* 严格模式: 只在开发模式中生效, 打包后会去除
* 检测危险操作, 比如废弃和不推荐的api
* 重复执行2次生命周期函数, 检测额外的副作用 render
*/
// <React.StrictMode>
<App/>
// </React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function