【发布时间】: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