React旧有生命周期和新生命周期的解析
Posted teayear
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React旧有生命周期和新生命周期的解析相关的知识,希望对你有一定的参考价值。
React组件生命周期(旧有格式)
新的生命周期
下面是旧有声明周期的案例演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/react.development.js"></script>
<script src="../js/react-dom.development.js"></script>
<script src="../js/babel.min.js"></script>
<script src="../js/prop-types.js"></script>
</head>
<body>
<div id="test"></div>
<!-- 制作组件 -->
<script type="text/babel">
class Count extends React.Component
//构造器;
constructor(props)
console.log('我是构造器');
super(props);
//初始状态;因为在构造器内部,所以,需要加this关键字;
this.state=count:0;
//组件将要挂载;
componentWillMount()
console.log('组件将要挂载...');
//加1按钮的回调;
add = () =>
//获取原始状态;
constcount=this.state;
//更新状态;
this.setState(count:count+1);
death= () =>
ReactDOM.unmountComponentAtNode(document.getElementById('test'));
//挂载完毕;
componentDidMount()
console.log('组件挂载完毕...');
//卸载组件;
componentWillUnmount()
console.log('组件卸载了...');
//组件更新
shouldComponentUpdate()
console.log('shouldComponentUpdate...');
return true;
//组件将要更新
componentWillUpdate()
console.log('componentWillUpdate...');
//组件更新
componentDidUpdate()
console.log('componentDidUpdate...');
//强制更新;
force= () =>
this.forceUpdate();
//渲染;
render()
console.log('render');
const count=this.state; //这句不要忘了加
return(
<div>
<h2>当前求和是:count</h2>
<button onClick=this.add>按钮测试</button>
<button onClick=this.death>卸载组件</button>
<button onClick=this.force>强制更新</button>
</div>
);
//调用;
ReactDOM.render(<Count/>,document.getElementById('test'));
</script>
</body>
</html>
以上是关于React旧有生命周期和新生命周期的解析的主要内容,如果未能解决你的问题,请参考以下文章