React-Native - TextInput 中的 Firebase 数据

React-Native - Firebase data in TextInput

我可以从 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}
            />

    )
 }

一定是工作:)

     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}
        />

)

}

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

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