【问题标题】:Error in then of updatingProfile firebase更新配置文件火力基地时出错
【发布时间】:2020-11-12 00:25:44
【问题描述】:

我正在尝试使用 firebase 在 updateProfile 的 then 中使用 redux 进行 api 调用,但出现此错误: TypeError: Cannot read property 'fetchProfile' of undefined

componentDidUpdate(prevProps) {

let user = firebase.auth().currentUser;
  user.updateProfile({
    displayName: `${form.firstName} ${form.lastName}`,
    email: form.email,
    phoneNumber: `${form.countryCode}${form.phone}`,
  }).then(function() {
    this.props.fetchProfile();
    Navigation.pop(componentId);
  }).catch(function(error) {
    console.log("error edit profile: ",error,error.response);
    this._registerFMSG.showMessage({
      message: '',
      description: error,
    });
  });
}

【问题讨论】:

  • this 可能不是指您认为该承诺中的对象。
  • 使用箭头函数,而不是常规函数。常规函数有自己的this 定义,箭头函数使用它们的上下文。
  • componentDidUpdate里面我怎么用箭头函数呢?
  • @RowanX .then(() => { this.props.fetchProfile()....

标签: reactjs firebase react-native firebase-authentication


【解决方案1】:

错误明确指出 this.props 未定义。

在 javascript 中,需要注意this 关键字的使用,因为它具有不同的上下文含义,具体取决于它的使用方式。

在这种情况下,this 很可能引用了一个您不想要的对象,因为您传入了一个由另一个对象调用的回调函数。

您的回电:

function() {
    this.props.fetchProfile();
    Navigation.pop(componentId);
  }

this 上的 MDN 是一个很好的参考:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

这应该适合你:

componentDidUpdate(prevProps) {
var currentProps = this.props
let user = firebase.auth().currentUser;
  user.updateProfile({
    displayName: `${form.firstName} ${form.lastName}`,
    email: form.email,
    phoneNumber: `${form.countryCode}${form.phone}`,
  }).then(function() {
    currentProps.fetchProfile();
    Navigation.pop(componentId);
  }).catch(function(error) {
    console.log("error edit profile: ",error,error.response);
    _registerFMSG.showMessage({
      message: '',
      description: error,
    });
  });
}

【讨论】:

  • 你能向我解释为什么 this.then 内部是明确未定义的吗?它在 componentDidUpdate 内的其他任何地方都可以使用
猜你喜欢
  • 2016-09-17
  • 1970-01-01
  • 2020-09-01
  • 2021-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
  • 2020-07-13
相关资源
最近更新 更多