【问题标题】:React-Native - Firebase data in TextInputReact-Native - TextInput 中的 Firebase 数据
【发布时间】:2018-01-16 06:27:26
【问题描述】:

我可以从 Firebase 检索数据并在之后立即显示。但是当我尝试在渲染中使用它时,它是空白的。我是 react-native 的新手,可能做错了什么。如何在渲染中使用 Firebase 中的数据?

这是我的代码:

    componentWillMount() {
    firebase.database().ref('/users/' +       userId).once('value').then(function(snapshot) {
                                                               var       DisplayEmail = snapshot.val().Email;                                                                       alert(DisplayEmail);
                                                               });

}

 render() { 
        return (

           {alert(this.props.DisplayEmail)}

          <TextInput style={styles.input}
            autoFocus = {true}
            autoCorrect = {false}
            autoCapitalize = "none"
            placeholder={this.DisplayEmail}
            keyboardType="email-address"
            underlineColorAndroid='transparent'
            editable={false}
            />

    )
 }

【问题讨论】:

    标签: firebase react-native firebase-realtime-database render


    【解决方案1】:

    当你想在渲染上显示一些东西时,你应该把它放在状态。通过更改状态,您将导致页面重新呈现并使用新状态进行更新。因此,当您进行 firebase 调用时,请将其添加到 state。

    componentWillMount() {
      firebase.database().ref('/users/' + userId).on('value', snapshot => {
        this.setState({ DisplayEmail: snapshot.val().Email });
      });
    }
    

    调用 set state 只是将您的状态更改与您当前的状态合并。现在你应该可以从渲染中调用状态并让它工作了。

    render() { 
      return (
        {alert(this.props.DisplayEmail)}
        <TextInput style={styles.input}
          autoFocus={true}
          autoCorrect={false}
          autoCapitalize="none"
          placeholder={this.state.DisplayEmail}
          keyboardType="email-address"
          underlineColorAndroid='transparent'
          editable={false}
        />
      )
    }
    

    【讨论】:

      【解决方案2】:

      它必须工作:)

           componentWillMount() {
           firebase.database().ref('/users/' + userId)
                     .on('value', snapshot => {
                             this.state = { DisplayEmail: snapshot.val().Email
               });
      
      }
      

       render() { 
          return (
      
             {alert(this.props.DisplayEmail)}
      
            <TextInput style={styles.input}
              autoFocus = {true}
              autoCorrect = {false}
              autoCapitalize = "none"
              placeholder={this.state.DisplayEmail}
              keyboardType="email-address"
              underlineColorAndroid='transparent'
              editable={false}
              />
      
      )
      

      }

      【讨论】:

      • 由于某种原因,警报显示未定义,文本输入为空白,当我从该屏幕返回到上一个屏幕时,值似乎显示一秒钟而没有给予任何控制并返回到上一个屏幕。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-11
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 2022-12-23
      相关资源
      最近更新 更多