Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

ngOnChanges事件不触发,求解

一个子组件接受一个list数组对象进行渲染,

<child [list]="list"></child>

数组对象是父组件通过http接口异步获取,然后在回调函数里面用list一个一个push进去像这样:

temArr.forEach(res => {
    http.getData().then(obj => {
        list.push(obj.data);
    })
})

然后我在子组件的ngOnChanges事件里面打印传过来的list是空的数组对象而且只打印了一次

ngOnChangee(changes: SimpleChanges) {
    for(let prorName in changes) {
        if(propName === 'list') {
            console.log(list) // []
        }
    }
}

后来我换了一种组装list的方法就正常了

temArr.forEach(res => {
    http.getData().then(obj => {
        list = [...list, obj.data];
    })
})

这种方法感觉和push的效果是一样的, 但是在ngOnChange里面的表现不一样,查了下资料好像也没看到很合理的解释,希望哪位大佬能解释一下,感谢!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

对象引用问题吧
下边写法, 相当于重定义了一个变量
引用地址改变了呀


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...