注意:State 的更新可能是异步的,React 可能会把多个 setState() 调用合并成一个调用
import React, { Component } from 'react'
class First extends Component {
constructor(props) {
super(props)
console.log("初始化state")
this.state = {
name: 'haijee',
num: 1,
list: [1, 2, 3]
}
}
render() {
return (
<>
{console.log("开始渲染dom")}
<div>
<ul>
{
this.state.list.map((item, index) => {
return (
<li key={index + item}>{item}</li>
)
})
}
</ul>
</div>
<div>
<button onClick={this.subtraction.bind(this)}>-</button>
<span>{this.state.num}</span>
<button onClick={this.addition.bind(this)}>+</button>
</div>
{console.log("渲染完毕")}
</>
);
}
addition() {
let num = this.state.num + 1
this.setState({
num: num
})
}
subtraction() {
console.log(this.state.num)
let num = this.state.num - 1
this.setState({
num: num
})
}
componentWillMount() {
console.log("初始化数据,渲染前:componentWillMount")
}
componentDidMount() {
console.log("DOM已经渲染了:componentDidMount")
}
componentWillReceiveProps(newProps) {
console.log("组件收到新的props:componentWillReceiveProps:" + newProps)
}
shouldComponentUpdate(newProps, newState) {
console.log("组件发生了更新,组件是否更新:shouldComponentUpdate:" + newState)
return true;
}
componentWillUpdate(nextProps, nextState) {
console.log("组件开始更新:componentWillUpdate")
}
componentDidUpdate(prevProps, prevState) {
console.log("组件完成更新:componentDidUpdate")
}
componentWillUnmount() {
console.log("组件被移除:componentWillUnmount")
}
}
export default First
网友评论