博主的参考资料
具体实例结果
操作为初始化组件,更新一次 state 中包含的值,移除该组件
测试代码
html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,minimum-scale=1.0"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>生命周期测试</title>
</head>
<body>
<div id="root"></div>
//此处引用打包后的 js 文件
</body>
</html>
下方代码内容为,往 html 中 id 为 “root” 的 div 标签添加 react 自定义组件 “ComponentTemplate “,并延迟 5 秒后移除,”ComponentTemplate ” 组件中显示一个 布尔值,单击后取反。
打包 js 前的文件 1
import React from 'react';
import ReactDOM from 'react-dom';
import ComponentTemplate from "./component/ComponentTemplate.jsx";
const main = <ComponentTemplate 初始化值={"默认值"}/>;
ReactDOM.render(main, document.getElementById('root'));
window.setTimeout(() => {
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
}, 5000);
打包 js 前的文件 2
import React from "react";
import ReactDOM from "react-dom";
class ComponentTemplate extends React.Component{
constructor(props) {
super(props)
this.state = {
show: true
}
console.log("constructor----------");
console.log(JSON.stringify(props));
}
componentWillMount() {
console.log("componentWillMount----------");
}
componentWillReceiveProps(nextProps, nextContext) {
console.log("componentWillReceiveProps----------");
console.log("nextProps:" + JSON.stringify(nextProps));
console.log("nextContext:" + JSON.stringify(nextContext));
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
console.log("shouldComponentUpdate----------");
console.log("nextProps:" + JSON.stringify(nextProps));
console.log("nextState:" + JSON.stringify(nextState));
console.log("nextContext:" + JSON.stringify(nextContext));
return true;// 返回 false 会阻止实际 dom 节点更新
}
render() {
return (
<div onClick={() => {
this.setState({show: !this.state.show});
}}>
{JSON.stringify(this.state.show)}
</div>
);
}
componentDidMount() {
//初始化时第一次渲染完实际 dom 时调用
console.log("componentDidMount----------");
console.log("");
}
componentDidUpdate(prevProps, prevState, snapshot) {
//除了初始化时第一次渲染完实际 dom,之后每次完成实际 dom 渲染时调用
console.log("componentDidUpdate----------");
console.log("prevProps:" + JSON.stringify(prevProps));
console.log("prevState:" + JSON.stringify(prevState));
console.log("snapshot:" + JSON.stringify(snapshot));
console.log("");
}
componentWillUnmount() {
//组件被移除的前一步执行(可用于清除监听事件等)
console.log("componentWillUnmount----------");
}
}
export default ComponentTemplate;