最近在换工作,很长一段时间没更新了,找工作的这段时间也不想闲着,没办法,作为一名女程序员来说,本来就有意见偏差,如果不学习的话就被淘汰。
看招聘信息的时候,一个规律就是,大厂喜欢用react,面试的时候喜欢问很基础的问题,比如js,node相关方面的,小型的就喜欢vue这方面的框架,问项目相关的多些,后面会出一集面试相关的东西,目前写下react相关入手级别
react生命周期(面试很多都问)
先来张生命周期图片
-
挂载,可以看出有两个生命周期,分布是组件挂载前componentWillMount(),和挂载中componentDidMount()。
- constructor():构造函数,以及完成了react数据初始化,它接受两个参数:props和contenxt,如果想用这两个函数,需使用super()传入这两个参数,注意:只要使用了constructor()就必须写super(),否则会导致this指向错误。
- componentWillMount():一边很少用,它更多是在服务端渲染时使用。它的组件以及经历过了constructor()初始化数据,但是还未渲染dom
- componentDidMount():组件第一次渲染完成,此时dom节点已经生成,可以在这里调用ajax请求,返回数据setState后组件会重新渲染 -
卸载:前componentWillUnmount (),卸载后componentDidmount ()
- 在此处完成组件的卸载和数据的销毁。clear你在组建中所有的setTimeout,setInterval;移除所有组建中的监听 removeEventListener。
有时候我们会碰到这个warning:
Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.
原因:因为你在组件中的ajax请求返回setState,而你组件销毁的时候,请求还未完成,因此会报warning
解决方法:
componentDidMount() {
this.isMount === true
axios.post().then((res) => {
this.isMount && this.setState({ // 增加条件ismount为true时
aaa:res
})
})
}
componentWillUnmount() {
this.isMount === false
}
- 渲染(分为更新过程)
- componentWillReceiveProps (nextProps)
1. 在接受父组件改变后的props需要重新渲染组件时用到的比较多
2. 接受一个参数nextProps
3. 通过对比nextProps和this.props,将nextProps的state为当前组件的state,从而重新渲染组件
- componentWillReceiveProps (nextProps)
componentWillReceiveProps(nextProps) {
nextProps.openNotice !== this.props.openNotice&&this.setSate({
openNotice:nextProps.openNotice
},()=>{
console.log(this.state.openNotice:nextProps)
//将state更新为nextProps,在setState的第二个参数(回调)可以打 印出新的state}
)
- shouldComponentUpdate(nextProps,nextState)
主要用于性能优化(部分更新)
唯一用于控制组件重新渲染的生命周期,由于在react中,setState以后,state发生变化,组件会进入重新渲染的流程,在这里return false可以阻止组件的更新
因为react父组件的重新渲染会导致其所有子组件的重新渲染,这个时候其实我们是不需要所有子组件都跟着重新渲染的,因此需要在子组件的该生命周期中做判断 - componentWillUpdate (nextProps,nextState)
shouldComponentUpdate返回true以后,组件进入重新渲染的流程,进入componentWillUpdate,这里同样可以拿到nextProps和nextState。 - componentDidUpdate(prevProps,prevState)
组件更新完毕后,react只会在第一次初始化成功会进入componentDidmount,之后每次重新渲染后都会进入这个生命周期,这里可以拿到prevProps和prevState,即更新前的props和state。- render()
render函数会插入jsx生成的dom结构,react会生成一份虚拟dom树,在每一次组件更新时,在此react会通过其diff算法比较更新前后的新旧DOM树,比较以后,找到最小的有差异的DOM节点,并重新渲染。
- render()