import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.css';
// import PropTypes from 'prop-types';
function computed() {
return new Promise(res => {
setTimeout(() => {
res(2)
}, 5000)
})
}
class A extends React.Component {
// static defaultProps = {m: 1, title: 444}//将传递进来的属性值设置默认值之后,才向下执行
constructor() {
super();
console.log('1-CONSTRUCTOR');
this.state = {n: 0, m: 0}
}
async componentWillMount() {
console.log('2 :第一次渲染之前', this.refs.HH)
let n = await computed();
this.setState({//改变状态
n: n
})
}
componentDidMount() {
console.log('4 :第一次渲染之后', this.refs.HH);
//真是项目中一般第一次组建渲染我们绑定的都是默认数据,第二次绑定的才是从服务器获取的
//数据
// setInterval(() => {
// this.setState({//改变状态
// n: this.state.n + 1
// })
// }, 10000)
/*
* 真是项目中在这个阶段一般做如下操作
* 1.控制状态信息更改的操作
* 2.从服务器获取数据,然后修改状态信息完成数据绑定
* */
}
componentWillReceiveProps(nextProps, nextContext) {
console.log('组建属性改变',this.props.n, nextContext.n);
}
shouldComponentUpdate(nextProps, nextState) {
/*
*nextProps:最新修改的属性信息
*nextState:最新修改的状态信息
* 在这个钩子函数中我们获取的STATE不是最新你修改的二十上一次的STATE值
*
* */
console.log("this.state.n", this.state.n)
console.log("nextProps", nextProps);//{m: 1,title:444}
console.log("nextState", nextState);//{n: 5, m: 0}
console.log('5 :是否允许下更新')//函数返回true就是允许更新否者不可以更新
if (nextState.n < 3) {
return true;
}
return true;
}
componentWillUpdate(nextProps, nextState) {
/*
* 这里获取的状态是更新之前的(和should相同也有两个参数存储最新的参数)
* */
console.log('6 :重新渲染之前')//函数返回true就是允许否者不可以
}
componentDidUpdate(ev) {
console.log('8 :组建更新之后')//函数返回true就是允许否者不可以
}
render() {
console.log('3 :render渲染')
return <div ref='HH'>
<h1>{this.props.n}</h1>
<h1>{this.state.n}</h1>
</div>
}
}
class B extends React.Component {
constructor() {
super();
this.state = {n: 1}
}
componentDidMount() {
setTimeout(() => {
this.setState({
n: 7
})
}, 7000)
}
render() {
return <div>
<A n={this.state.n}></A>
</div>
}
}
let root = document.getElementById("root")
ReactDOM.render(<B title="5555"></B>, root)
React 生命周期函数的使用
最新推荐文章于 2021-11-09 18:31:02 发布