【问题标题】:What is the best way of changing a specific individual value for Firebase database in React Native?在 React Native 中更改 Firebase 数据库的特定单个值的最佳方法是什么?
【发布时间】:2020-04-22 15:02:43
【问题描述】:

我在注册用户时使用的逻辑是将他们的详细信息添加到数据库中的路径以及 Firebase 身份验证中。从理论上讲,这些值会更容易操纵。 我的目标是创建一个 Formik 表单,它将接受登录用户的用户名的现有值,在文本输入中显示该值以供用户更改,然后更新 Firebase 数据库中的值。任何人都可以帮忙吗?

import React, {Component} from 'react';
import {TextInput, View, Button, StyleSheet} from 'react-native';
import {Formik} from 'formik';
import Firebase from 'firebase';
import 'firebase/database';
import 'firebase/auth';

export default class ChangeUsername extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentUsername: '',
      Username: '',
    };
  }

  getUsername() {
    const userKey = Firebase.auth().currentUser.uid;
    const userRef = Firebase.database().ref('users/' + userKey);

    userRef.once('value').then(snapshot => {
      const user = snapshot.val();
      this.setState({currentUsername: user.username});
      console.log(this.state.currentUsername);
    });
  }

  changeUsername() {
    const userKey = Firebase.auth().currentUser.uid;
    const userRef = Firebase.database().ref('users/' + userKey);
    userRef.update({
      username: this.state.Username,
    });
    console.log(this.state.Username);
  }

  componentDidMount() {
    this.getUsername();
    this.changeUsername();
  }

  render() {
    return (
      <View>
        <Formik
          initialValues={{
            username: this.state.currentUsername,
          }}
          enableReinitialize={true}
          onSubmit={this.changeUsername()}>
          {props => (
            <View>
              <TextInput
                style={style.txtInput}
                onChangeText={text => this.setState({Username: text})}
                value={this.state.currentUsername}
              />
              <Button title="Submit" onPress={props.handleSubmit} />
            </View>
          )}
        </Formik>
      </View>
    );
  }
}

我还尝试使用 React 功能组件而不是类来创建表单。 当前发生的是文本输入保持为空,并且每次我尝试在其中输入内容时都会恢复为空。另外,数据库中的用户名将更新为我设法在它消失之前输入的字母。 IE。我输入字母“p”,用户名将更新为firebase数据库中的字符串“p”,然后文本输入将被清除。

【问题讨论】:

  • 您共享的代码有什么问题?例如:当您在调试器中单步执行代码时,哪一行没有按照您的预期执行?问题描述越清晰,就越有可能有人可以提供帮助。
  • 所以当我使用 console.log(this.state.currentUsername) 和 console.log(Username) 时,两者都没有返回任何内容。 currentUsername 应该读取数据库中现有的 'username' 值,并创建 Username 以获取用户在文本输入中输入的值,然后将其设置为新用户名。你还有什么需要知道的吗?
  • 我在您的原始 sn-p 中没有看到任何 console.log。请确保您的问题包含所有相关代码作为一个最小的 sn-p,以便我们可以看到它们之间的关系。
  • 我已经更新了代码
  • 调用setState 是一个异步操作,所以这不起作用:this.setState({currentUsername: user.username}); console.log(this.state.currentUsername); console.log 运行时,状态可能还没有更新。请参阅stackoverflow.com/questions/41446560/… 了解如何正确处理这种情况。

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


【解决方案1】:

我没有尝试直接从数据库中获取用户名,而是解决了这个问题,而是从 Firebase 身份验证中的 displayName 字段中提取了它。

import React, {useState} from 'react';
import {TextInput, View, Button, StyleSheet} from 'react-native';
import Firebase from 'firebase';
import 'firebase/database';
import 'firebase/auth';
import {Formik} from 'formik';
import {userKey} from '../config/ReusableVariables';

export default function ChangeUsername() {
  //obtain the user and username of logged in user as objects
  const user = Firebase.auth().currentUser;
  const currentUsername = Firebase.auth().currentUser.displayName;

  //set username variable that will be changed as the existing username
  const [Username, setUsername] = useState(currentUsername);

  //function that rewrites username in firebase authentication and database
  function changeUsername(value) {
    user.updateProfile({displayName: value.username}).then(() => {
      Firebase.database()
        .ref('users/' + userKey)
        .update({username: value.username});
    });
  }
  return (
    <View>
      <Formik
        initialValues={{
          username: currentUsername,
        }}
        enableReinitialize={true}
        onSubmit={values => {
          changeUsername({
            username: Username,
            displayName: Username,
            //values in authentication and database changed to newly set Username
          });
        }}>
        {props => (
          <View>
            <TextInput
              style={style.txtInput}
              onChangeText={
                text => setUsername(text)
                //variable Username will be set to whatever is typed into this text input
              }
              value={Username}
            />
            <Button
              title="Submit"
              onPress={
                props.handleSubmit
                //links button to onSubmit function in Formik
              }
            />
          </View>
        )}
      </Formik>
    </View>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-09
    • 2020-09-21
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多