【问题标题】:React Native this.setState of textReact Native this.setState 的文本
【发布时间】:2020-08-27 21:35:30
【问题描述】:

我是 React Native 的新手,当我使用 this.setState() 更改值时,我无法更新我的变量。单击按钮时,我正在调用此函数:

    const updateName = () => {
        var user = firebase.auth().currentUser;
        user.updateProfile({
            displayName: "Test Test"
        }).then(function() {
            alert('Name changed')
        }).catch(function(e) {
            alert(e)
        })
        this.setState({ userFullName: firebase.auth().currentUser.displayName })
    }

这会将当前用户的显示名称更新为“Test Test”,我希望此更改能够反映在屏幕上。它当前显示在 userFullName 变量中,但我收到 TypeError: undefined is not an object。有人知道怎么做吗?

【问题讨论】:

  • 没有所有代码很难
  • 你还需要看什么?

标签: react-native react-native-firebase


【解决方案1】:

如果我在做这个,我会写一个更像这样的函数:

const updateName = async (displayName) => {
    this.setState({ userFullName: displayName })
    try {
        var user = firebase.auth().currentUser;
        await user.updateProfile({
            displayName
        })
        alert('Name changed')
    } catch (e) {
        alert(e)
        this.setState({ userFullName: firebase.auth().currentUser.displayName })
    }
}

这并不能回答您收到 TypeError: undefined is not an object. 错误的原因,但是,这将确保您的 UI 在您保存新的 displayName 时响应。

现在,对于这样的一般性错误,很难说出究竟是什么问题,但我要检查的变量是 undefined 将是 firebasefirebase.auth().currentUser。似乎该错误可能是指这些变量中的任何一个,因为它们被作为对象访问。

【讨论】:

  • 感谢您的回答。我在 Promise 拒绝中遇到同样的错误
  • 是否 userFullName 必须是一个全局变量,这就是为什么会发生未定义的错误?因为我知道 firebase 部分不是未定义的
  • 所以我刚刚意识到您使用类语法来设置状态而不是钩子语法。如果您的 React 组件是一个类,您需要在 updateName 之前删除 const,以便您的函数是类成员函数。这应该使this 绑定到正确的东西。看看这是否改变了什么。
猜你喜欢
  • 2020-08-26
  • 1970-01-01
  • 2018-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多