React生命周期
1、react组件的生命周期
1、生命周期指的是组件从初始化开始到结束的过程 或者是生命周期是描述ract组件从开始到结束的过程
2、每个react组件都具有生命周期
3、react都对组件通过生命周期给予的钩子函数进行管理
2、钩子函数
指的是系统某些状态和参数发生改变的时候,系统立马去通知对应处理的函数 叫做钩子函数
一方面又变动,另一方面立马去处理。
3、react组件经历总体阶段
1、mounted阶段 加载阶段 或者说初始化阶段 这个阶段组件由jsx转换成真实dom
2、update阶段 组件运行中阶段 或者更新阶段 当组件修改自身状态,或者父组件修改子组件属性的时候发生的阶段
3、umount阶段 组件卸载阶段 这个一般是组件被浏览器回收的阶段
我们对Markdown编辑器进行了一些功能拓展与语法支持,除了标准的Markdown编辑器功能,我们增加了如下几点新功能,帮助你用它写博客:
React生命周期整体流程:
1.实例化阶段
getDefaultProps 取得默认属性
getInitialState 初始化状态
componentWillMount 即将进入dom
render 描画dom
componentDidMount 已经进入dom
//用ajax发起数据请求在componentWillMount()和componentDidMount()这两个里面都可以
//此函数在render()调用之前执行
componentWillMount() {
console.log("即将加载");
console.log(this.refs.tit); //undefined
$.ajax({
type: "get",
url: "http://jx.xuzhixiang.top/ap/api/productlist.php",
dataType: "json",
success: function(response) {
console.log(response);
}
});
}
//此函数在render()调用之后执行
componentDidMount() {
console.log("加载完成");
console.log(this.refs.tit); //<h2>生命周期</h2>
}
2、具体的声明函数周期—运行中阶段 数据更新过程
运行中阶段只有在父组件修改了子组件的属性或者说一个组件修改自身的状态才会发生的情况
1、组件将要接受新值componentWillReceiveProps(已加载组件收到新的参数时调用)
2、组件是否更新 shouldComponentUpdate (影响整个项目的性能,决定视图的更新)
3、组件即将更新 componentWillUpdate
4、必不可少的render
5、组件更新完毕时运行的函数 componentDidUpdate
(1)组件修改了自身状态值
componentWillReceiveProps() {
console.log("组件即将接收新值");
}
//修改了自身属性值
shouldComponentUpdate() {
return true;
// return false; 可以避免视图不必要的更新 为false函数不会更新
}
componentWillUpdate() {
console.log("will update");
}
componentDidUpdate() {
console.log("did update");
}
(2)父组件修改了子组件的属性
<div id="out"></div>
<script type="text/babel">
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
info: ""
};
}
tap() {
console.log(this.refs.tit.value);
// console.log(this.refs.tit.innerHTML);
this.setState({ info: this.refs.tit.value });
//销毁组件 组件被浏览器回收
// ReactDOM.unmountComponentAtNode(document.getElementById("out"));
}
render() {
return (
<div>
<h2>父组价</h2>
<input type="text" ref="tit" />
<button onClick={this.tap.bind(this)}>父组件传给子组件</button>
<hr />
<Child name={this.state.info} />
</div>
);
}
}
//子组件
class Child extends React.Component {
constructor(props) {
super(props);
}
render() {
// console.log(this.props.name);
return (
<div>
<h2>子组件</h2>
<p>接收父组件的值:{this.props.name}</p>
</div>
);
}
//这四个函数都会被执行
//运行中阶段 数据更新过程
componentWillReceiveProps() {
console.log("组件即将接收新值");
}
shouldComponentUpdate() {
return true;
// return false; 可以避免视图不必要的更新 为false函数不会更新
}
componentWillUpdate() {
console.log("will update");
}
componentDidUpdate() {
console.log("did update");
}
3、销毁时 componentWillUnmount
卸载组件
ReactDOM.unmountComponentAtNode(‘节点’)
//销毁组件 组件被浏览器回收
// ReactDOM.unmountComponentAtNode(document.getElementById("out"));