react中useEffect对应class 哪些生命周期,hooks的优缺点是什么
- 首次渲染 componentDidMount
- 更新 componentDidUpdate
- 销毁 componentWillUnMount
优点:代码可读性强,维护起来比较方便,不需要记太多的生命周期函数
缺点:只兼容了componentDidMount、componentDidUpdate还有componentWillUnmount这三个生命周期,对于getSnapshotBeforeUpdate和componentDidCatch等其他的生命周期没有支持
react的调和过程
调和:react在更新阶段很巧妙的对比原有的virtural DOM 和新生成的virtural DOM找出两者的不同之处,根据不同来修改DOM树,只需要做最小的必要改动。在执行这个的过程总,就叫做调和
触发调和的过程:
render函数
setState
componentWillMount,componentWillreceviceprop
react diff 算法
raect对普通股的diff算法实行了三个策略,从而将时间复杂度O(n^3)将为o(n)
- 层级对比:在开发过程中极少出现DOM的跨层级移动,忽略DOM节点的跨层级移动。假如出现跨级移动的,会处理成多的为新增,少了的就删除了
- 组件对比:同类型的两个组件,直接比较Virtual DOM树,不同类型的组件将会被判定作为脏组件(dirty component)处理,直接删除或创建新组件
- 节点对比:对于同一层级的一组子节点,通过分配唯一唯一key值进行区分
react connect 实现原理
- 在原应用组件上包裹一层,使原来整个应用称为Provider的子组件
- 接收redux的store作为props,通过context对象传递给子孙组件的connect
- 使用方法:connect(mapStateToProps,mapDispatchToProps)(组件)
connect源码部分
function connect (mapStateToProps,mapDispatchToProps, mergeProps, options = {}){
return function wrapWithConnect(WrappedComponent) {
class Connect extends Component {
constructor(props, context) {
// 从祖先Component处获得store
this.store = props.store || context.store
this.stateProps = computeStateProps(this.store, props)
this.dispatchProps = computeDispatchProps(this.store, props)
this.state = { storeState: null }
// 对stateProps、dispatchProps、parentProps进行合并
this.updateState()
}
shouldComponentUpdate(nextProps, nextState) {
// 进行判断,当数据发生改变时,Component重新渲染
if (propsChanged || mapStateProducedChange || dispatchPropsChanged) {
this.updateState(nextProps)
return true
}
}
componentDidMount() {
// 改变Component的state
this.store.subscribe(() = {
this.setState({
storeState: this.store.getState()
})
})
}
render() {
// 生成包裹组件Connect
return (
<WrappedComponent {...this.nextState} />
)
}
}
Connect.contextTypes = {
store: storeShape
}
return Connect;
}
}
react性能优化
- 对组件控制,当达到一定的容量后需要对组件拆分,做更细粒度的控制
- 使用useMemo对react元素缓存,useCallback对函数缓存
- 类组件使用shouldComponentUpdate,来决定是否需要重新render
render和renderToString的区别
renderToString()方法由ReactDOMServer提供,在这里已为你定义成全局变量。这个方法接受一个 React 元素作为参数。用它来把App渲染成字符串。
什么是redux,以及redux与mobox之间的区别
redux 是一个独立专门用于做状态管理的js库,集中式管理react应用中多个组件共享的状态
![在这里插入图片描述](https://img-blog.csdnimg.cn/938af44f5dd84229b15537fc0b8a828e.webp#pic_center)
redux三个核心概念
-
action 要执行的行为对象
-
reducer 返回一个新的状态,也可以理解为在这个里面执行为同步操作
共同点: -
为了解决状态管理婚恋,无法有效同步的问题统一管理应用状态
-
操作更新状态方式统一,并且可控(通常以action方式提供更新状态的途径)
-
支持将store与react组件连接,如react-redux,mobx-react
调用setState之后会发生什么?
在代码中华调用setState函数后,react会将传入的参数对象与组件当前的状态合并,然后出发调和过程,经过调和过程,react会以相对高效的方式根据新的状态构建react元素树并重新渲染整个UI界面,react会自动计算出新的树与老树的节点之间的差异,然后根据差异对戒面进行最小化渲染,从而保证了按需更新,而不是全部渲染。
react生命周期函数有哪些
初始化阶段
- getDefaultprops :获取实例的默认属性
- getInitialState:获取每个实例的实话状态
- componentWillMount:组件即将被装载,渲染到页面上
- render:组件在这里生成虚拟DOM节点
- componentDidMount:组件真正被装载之后
运行中状态
componentWillreceiverProps :组件将要被接收到属性的时候调用
shouldComponentUpdate:组件接收到新属性或者新状态的时候,渲染是否重新渲染