1: React 生命周期函数
第一条路线: 从 setState() 更新组件触发
定义一个容器:
<div id="test"></div>
<script type="text/babel">
// 定义一个组件
class Count extends React.Component {
// constructor 构造器
constructor(props) {
super(props)
// 初始化状态
this.state = {count: 0}
}
// 事件处理函数 自定义方法使用赋值语句加上箭头函数
add = ()=> {
// 获取原来状态
let { count } = this.state;
this.setState({count: count + 1});
}
// 卸载组件按钮的回调函数
unLoad =() => {
ReactDOM.unmountComponentAtNode(document.getElementById('test'));
}
组件将要挂载时候的钩子
componentWillMount() {
console.log('组件将要挂载')
}
组件挂在完毕的钩子
componentDidMount () {
console.log('组件挂载完毕')
}
组件将要卸载的钩子
componentWillUnmount() {
console.log('组件将要卸载')
}
// 控制组件更新"开关" 或者 "阀门"
// 该函数会返回一个boolean 值, true 为组件状态需要更新
如果为 false: 说明组件状态不需要更新。
// 默认情况下返回的true; 如果不写该函数面默认返回就是false;
shouldComponentUpdate() {
return true;
}
// 组件将要更新钩子函数 (组件将要更新的回调函数)
componentWillUpdate() {
console.log('组件将要更新')
}
// 组更新完成之后
componentDidUpdate() {
console.log("组件完成更新之后")
}
// 然后render函数是 React中一个重要生命
render() { // render 函数必须要有返回值
return { // return 中书写jsx 语法
<div>
<h2>当前求和为: {this.state.count} </h2>
<button @onClick={this.add}></button>
<button @onClick={this.unLoad}></button>
</div>
}
}
}
-----------------------------------------------------------------
组件状态更新的顺序
1: shouldComponentUpdate() {} 该函数返回一个boolean 值;
如果返回值为true; 则继续向下执行其他函数
2: componentWillUpdate() {} 组件将要更新
3;render() 渲染函数
4: componentDidUpdate() 组件更新之后钩子函数
-----------------------------------------------------------------
第二条路线: 从forceUpdate() 角度出发
forceUpdate() 强制更新组建 setState 正常修改状态
forceUpdate() 表示强制更新组件
forceUpdate() 方法: 表示不修改状态, 直接更新组件
如果修改状态, 就会触发以下四个生命周期
shouldComponentUpdate() {} 默认返回为 true;
componentWillUpdate() {} 组件将要更新
render() {} 函数
componenDidUpdate() {} 组件更新完毕
// 组件强制更新 forceUpdate() 组件强制更新
就会触发一下函数:
componentWillUpdate() {} 函数, 组件将要更新
render() {} render() 渲染函数
componentDidUpdate() {} 组件更新完毕
组件更新有三条路线: