teste(){
console.log('a');
}
componentDidMount() {
// firebase things?
firebase.database().ref('Matheus').on('value', function(snapshot){
itens = snapshot.val();
itens.forEach((data) => {
firebase.storage().ref(data).getDownloadURL().then(this.teste);
});
});
代码有效。只是不可能调用函数this.teste
context of this
在内部函数中运行时发生了变化。
将 this
存储在临时变量中以在函数内部使用它:
componentDidMount() {
const that = this; // holding the context for this
// firebase things?
firebase.database().ref('Matheus').on('value', function(snapshot){
itens = snapshot.val();
itens.forEach((data) => {
firebase.storage().ref(data).getDownloadURL().then(that.teste); // using that instead of this
});
});
或者使用 arrow function它将为 this
使用词法上下文:
componentDidMount() {
const that = this; // holding the context for this
// firebase things?
firebase.database().ref('Matheus').on('value', (snapshot) => { // arrow function instead
itens = snapshot.val();
itens.forEach((data) => {
firebase.storage().ref(data).getDownloadURL().then(that.teste);
});
});