javascript - React 不调用函数

标签 javascript reactjs firebase react-native this

<分区>

  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);
   });
 });

关于javascript - React 不调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52573380/

相关文章:

firebase - onMessage 回调函数未触发

firebase - 如何在 Flutter 中使用 Firestore withConverter

javascript - 当另一个复选框被重叠选中时取消全部选中/选中一个复选框

javascript - 获取同级组件中的光标位置

ios - Firebase Auth 链接提供商 Google 登录问题?

reactjs - 响应 useEffect 以在组件安装和依赖项更改时运行

javascript - React 中的 PSD.js 错误 fs.readFileSync 不是函数

php - 如何集成对自动分页插件的支持

javascript - 从 Node.js 更新 MySQL - 如何判断零行是否受到影响?

javascript - 加载延迟extjs