<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="test"></div>
</body>
</html>
<script type="text/babel">
class Count extends React.Component{
constructor(props) {
console.log('Count-constructor');
super(props);
//初始化状态
this.state={count:0}
}
//组件将要挂载的钩子
componentWillMount() {
console.log('Count---componentWillMount');
}
//组件挂载完毕后的钩子
componentDidMount() {
console.log('Count---componentDidMount');
}
//组件将要卸载的钩子
componentWillUnmount() {
console.log('Count--componentWillUnmount');
}
//是否要进行数据更新(不写钩子默认为true,若写则必须写返回值)
shouldComponentUpdate() {
console.log('Count--shouldComponentUpdate');
//返回 Boolean值,true可以调用render
return true
}
//组件将要更新
componentWillUpdate() {
console.log('Count--componentWillUpdate');
}
//数据更新完毕
componentDidUpdate() {
console.log('Count--componentDidUpdate');
}
render(){
console.log('Count---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>
)
}
Add=()=>{
//获取原始状态
const {count} =this.state
//更新状态
this.setState({count:count+1})
}
death=()=>{
ReactDOM.unmountComponentAtNode(document.querySelector("#test"))
}
//强制更新数据
force=()=>{
this.forceUpdate()
}
}
ReactDOM.render(<Count/>,test)
</script>