问题描述
我试图了解Stencil生命周期文档的@Watch()
部分:https://stenciljs.com/docs/component-lifecycle
对我来说,@Watch()
实际开始观看时并未清楚显示上图。
似乎有一种情况,甚至在{strong> @Watch()
之前甚至在{strong> {1}}之前触发了componentwillLoad()
钩子,例如,在React与React.createRef()
中使用了Stencil组件时。这些情况并非总是可重复的-这意味着可能是种族情况。
这就是为什么我想从@Watch()
的哪个特定时间开始活动?
解决方法
从链接的文档页面的图形中可以看出,每次观察到的prop或状态值发生变化时,都会调用一个@Watch()
装饰方法。这与将组件连接到DOM时发生的willLoad / willRender / render / didRender / didLoad / didUpdate周期无关。
@Component({ tag: 'my-comp' })
export class MyComp {
@Prop() input = 'foo';
@State() repeated: string;
@Watch('input')
onInputChange() {
this.repeated = this.input + this.input;
}
componentWillLoad() {
this.onInputChange(); // can manually call the watcher here
}
render() {
return this.repeated;
}
}
<script>
const myComp = document.createElement('my-comp');
// currently `repeated` would be undefined because the component has not yet rendered
myComp.input = 'foobar'; // now `repeated` *should* be `foobarfoobar`
</script>
(说 *应该* ,因为我还没有测试过)
,如 stencil change @Prop() detection 所述,属性的 @Watch 装饰器会在属性值更改时触发,但不会在属性初始设置时触发。
要捕获初始化,您必须在传递属性值的 componentWillLoad 上触发处理程序。
@Watch('name')
onNameChanged(newValue: string,oldValue: string) {
this._name = newValue;
}
componentWillLoad(){
this.onNameChanged(this.name);
}