stenciljs 学习三 组件生命周期
stenciljs 组件包含好多生命周期方法, will did load update unload
实现生命周期的方法比价简单类似 componentWillLoad 。。。。,使用typescript
比较方便,实现接口就可以了
参考实现
import { Component, Prop,ComponentDidLoad,ComponentDidUnload,ComponentWillLoad,ComponentWillUpdate } from '@stencil/core';
@Component({
tag: 'my-component',
styleUrl: 'my-component.css',
shadow: false
})
export class MyComponent implements ComponentDidLoad ,ComponentDidUnload,ComponentWillLoad,ComponentWillUpdate{
@Prop() first: string;
@Prop() last: string;
componentWillLoad(){
console.log("Component will to be rendered")
}
componentDidLoad() {
console.log('Component has been rendered');
}
componentWillUpdate() {
console.log('Component will update and re-render');
}
componentDidUpdate() {
console.log('Component did update');
}
componentDidUnload() {
console.log('Component removed from the DOM');
}
render() {
return (
<div >
Hello, World! I'm {this.first} {this.last}
</div>
);
}
}
状态渲染
推荐的做法是任何状态的更新在 componentWillLoad() 或者 componentWillUpdate()方法中
这些方法是在render 之前调用的,可选的是使用componentDidLoad()或componentDidUpdate()
方法更新状态将导致另一次重新渲染,对于性能来说不是很好。
如果必须更新状态componentDidUpdate(),则可能会使组件陷入无限循环。如果更新状态componentDidUpdate()
是不可避免的,那么该方法还应该有一种方法来检测道具或状态是否“脏”(数据实际上是不同的还是与以前相同)。
通过执行脏检查,componentDidUpdate()可以避免呈现相同的数据,然后componentDidUpdate()再次调用。
生命周期的层次结构
基本原则就是最深的组件首先完成加载,然后componentDidLoad()冒泡调用。
参考组件
<cmp-a>
<cmp-b>
<cmp-c></cmp-c>
</cmp-b>
</cmp-a>
渲染顺序
- cmp-a - componentWillLoad()
- cmp-b - componentWillLoad()
- cmp-c - componentWillLoad()
- cmp-c - componentDidLoad()
- cmp-b - componentDidLoad()
- cmp-a - componentDidLoad()
异步生命周期方法
生命周期方法还可以返回promises,允许方法异步检索数据或执行任何异步任务
参考:
componentWillLoad() {
return fetch('/some-data.json')
.then(response => response.json())
.then(data => {
this.content = data;
});
}
说明
componentDidLoad 只调用一次
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2017-09-26 envoy 功能介绍
2017-09-26 envoy 测试试用