【问题标题】:Checking if an instance in Firebase already exists检查 Firebase 中的实例是否已存在
【发布时间】:2017-11-14 02:10:27
【问题描述】:

我正在尝试在写入之前检查用户输入的字符串是否已存在于我的数据库中。

这是我目前拥有的:

火力基地:

players
      id: 
      playerContent: Firstname Lastname
class PlayerForm extends Component {
  constructor(props) {
    super(props);
    this.state= {
        newPlayerContent: '',
        exists: null
    };

    this.writePlayer = this.writePlayer.bind(this);
    this.checkIfUserExists = this.checkIfUserExists.bind(this);
}


checkIfUserExists(newPlayerContent) {
var playersRef = firebase.database().ref().child('players');

playersRef.once('value', function(snapshot) {
    if (snapshot.hasChild(newPlayerContent)) {
        this.setState({ exists });
    }
  })
 }

writePlayer(){
    if(this.exists !== null){
    this.props.addPlayer(this.state.newPlayerContent);
    this.setState({
        newPlayerContent: '',
        })
    }
    else{
    console.log("This player already exists.")
    }
}

无论如何,它一直允许它进入。我对 checkIfUserExists 函数有点不确定,特别是如果我在 firebase 中访问我的数据。我正在将 newPlayerContent 的内容输出到控制台,这实际上是我输入的内容,但我不确定检查是否正常。这里有什么突出的吗?

提前致谢。

【问题讨论】:

  • 我不确定 firebase 是如何工作的,但在你的 checkIfUserExists 函数中你有 this.setState({ exists }); 但没有实际的 exists 变量。所以我假设你想做this.setState({ exists: true });

标签: javascript reactjs firebase firebase-realtime-database


【解决方案1】:

我使用 duplicate 而不是存在 .. 但这段代码似乎完全符合我的意愿。如果它已经在名称字段 (playerContent) 中看到该玩家名称,它不会让您将另一个人添加到数据库中。

var playersRef = firebase.database().ref();
playersRef.child('players').orderByChild("playerContent").equalTo(newPlayerContent).once("value",snapshot => {
    const userData = snapshot.val();
    if (userData){
      console.log("exists!");

      this.state.duplicate = true;

      console.log(this.state.duplicate)
    }
    else{
      console.log("does not exist.")
      this.state.duplicate = false;
      console.log(this.state.duplicate)
    }
});

在writePlayer函数中:

if(this.state.duplicate !== true){
    this.props.addPlayer(this.state.newPlayerContent);
    this.setState({
        newPlayerContent: '',
        })
    }
    else{
    console.log("This player already exists.")
    }

想一想,这确实会引发警告——

不要直接改变状态。使用 setState() 反应/无直接突变状态

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多