我们先来看看Component的定义,这是React的基础组件,我感觉这个就和flutter的Widget相似,但是因为我才接触RN如果差距很大的话,我后面补一篇文章详细谈谈。
// Base component for plain JS classes
interface Component<P = {}, S = {}, SS = any> extends ComponentLifecycle<P, S, SS> { }
那么Component的生命周期管理我们就看看ComponentLifecycle中定义了哪些生命周期方法:
1、
componentDidMount?(): void;
componentDidMount方法在安装组件后立即调用,在此处设置状态将触发重新渲染。我个人觉得类似于flutter的initState()用法。
2、
shouldComponentUpdate?(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): boolean;
调用shouldComponentUpdate方法可以确定props和state的更改是否应该触发重新渲染,Component该方法总是返回true,可以重写方法,按照自己的要求返回。PureComponent对props和state进行浅层比较,如果任何props或者state发生更改,则返回true。如果返回false,则不会调用Component的render、componentWillUpdata和componentDidUpdata方法。PureComponent由于是浅比较的原因,我个人建议新手还是不要在子组件中使用,把握不住呀哈哈。
3、
componentWillUnmount?(): void;
componentWillUnmount方法在组件销毁之前立即调用,在此方法中执行任何必要的清理,例如却笑网络请求,取消监听,取消计时器等等,或者清理在componentDidMount中创建的任何DOM元素。我这个地方理解为flutter的dispose()方法,
4、
componentDidCatch?(error: Error, errorInfo: ErrorInfo): void;
componentDidCatch方法捕获子体组件中生成的异常。未处理的异常将导致整个组件树卸载。