编写今天文章之前带给大家的就是,我编写的绝大多数都是基础,因为自己也是重新学习了React也没有项目经验,很多坑以及很多方法是极其不熟练的,希望大家之后能找一些书深入学习
React的生命周期与Vue的生命周期,看似简单,实则我认为是很难很复杂的一部分,这个需要长期的工作经验才能领悟
class HelloComponent extends React.Component{
constructor(props){
super(props)
}
render(){
return (<h1>React</h1>)
}
}
ReactDOM.render(<HelloComponent/>,document.getElementById('div'))
初始化代码要很熟练了
一个组件完整的生命周期包含实例化阶段、活动阶段、销毁阶段三个阶段。每个阶段又由相应的方法管理。
过程中涉及三个主要的动作术语:
mounting:表示正在挂接虚拟DOM到真实DOM。
updating:表示正在被重新渲染。
unmounting:表示正在将虚拟DOM移除真实DOM。
每个动作术语提供两个函数:
omponentWillMount()
componentDidMount()
componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)
componentWillUnmount()
本文主要理解这五个函数,卸载组件先不写
将生命周期方法添加到类中
以后有机会深入,此时了解先后顺序即可
class HelloComponent extends React.Component{
constructor(props){
super(props)
this.state={name:'React'}
console.log('1....State')
}
componentWillMount(){
console.log('2...componentWillMount');
}
componentDidMount(){
console.log('3...componentDidMount');
}
componentWillUpdate(){
console.log('4...componentWillUpdate');
}
componentDidUpdate(){
console.log('5...componentDidUpdate');
}
handleClick(){
this.setState({name:'Reacts'})
}
render(){
return (
<div>
<h1> {this.state.name}</h1>
<button onClick={this.handleClick.bind(this)}>CHange</button>
</div>
)
}
}
ReactDOM.render(<HelloComponent/>,document.getElementById('div'))
再强调两个点,return后面返回的HTML有且只有一个根元素,此处为什么加()
如果不加()return 后面一定要跟元素,加()便于我们代码美观一点
ES6的写法函数默认不绑定this,因此在事件中绑定类实例
因为实际开发中不可能就一个事件,还是建议在constructor中绑定事件的this,便于维护
看看效果
页面初始化的时候,更新钩子未触发,挂载钩子成功触发并且state是第一
测试的时候哪怕你更换方法位置也是一样的,因为函数跟位置是没关系的,但是我们按顺序写更容易理解
此时我们点击事件改变state
React变为Reacts 成功触发了更新钩子函数
有了生命周期我们能做许许多多的事情,Vue最常见的就是数据渲染,比如我们现在假装定义一个ajax请求
tick(){
console.log('我是打印的数据')
}
将此函数挂载到生命周期中
componentWillMount(){
this.tick()
console.log('2...componentWillMount');
}














网友评论