我希望将Firebase数据库中的值存储到RN项目中。
我能够通过终端正确地记录对象。
我没有正确更新我的setState,团队数组应该用teamScore填充。
下面是我的代码:
class WesternIndex extends React.Component {
constructor(props) {
super(props);
this.state = {
dallasTeam: [],
denverTeam: [],
goldenStateTeam: [],
};
}
componentDidMount() {
this.getRef().child('Western_Teams').on('child_added', snapshot => {
if (snapshot.exists()) {
// console.log(snapshot.val()) //val logs Object
// console.log(snapshot.key) //key logs city name
}
let that = this;
this.getRef().child('Western_Teams').once('child_added', function(snapshot){
let scores = [];
snapshot.forEach(function(data) {
let score = {
id: data.val().key
}
const printThis = scores.push(score);
console.log('prints = ', (printThis)); // prints the number 1, 15 times
that.setState({
teamScore: scores
});
});
})
})
});
}
getRef = () => {
return firebase.database().ref();
}
答案 0 :(得分:0)
您似乎(偶然地?)为Firebase实时数据库注入了两个侦听器。另外,请注意on('child_added')
侦听器将同时触发一个孩子,因此您最初的forEach
可能是错误的。
尝试以此替换您的componentDidMount
componentDidMount() {
this.getRef().child('Western_Teams').on('child_added', snapshot => {
if (snapshot.exists()) {
this.setState({
teamScore: scores.concat(data.val);
});
}
});
}
虽然我不完全了解您要实现的目标,但是此代码段应该可以正常工作,并引导您朝正确的方向前进。
答案 1 :(得分:0)
似乎您的函数被调用了15次。因此,每次都重新创建数组 String user = "root";
String pass = "";
String url = "jdbc:mysql://127.0.0.1:3306/provapaoo_22_06_2018";
String takeVotes = String.format("select `Total Votes` "
+ "from `%s` where id= ?", nameOfTable);
String addVote = String.format("update `%s` set "
+ "`Total votes` = ?", nameOfTable);
try{
Connection conec =
DriverManager.getConnection(url, usuario, senha);
PreparedStatement comand =
conexão.prepareStatement(takeVotes);
comando.setInt(1, id);
ResultSet result = comand.executeQuery();
int qtdVotes = 0;
while(resultado.next()){
qtdVotes = result.getInt("Total Votes");
}
qtdVotes++;
comand = conec.prepareStatement(addVote);
comand.setInt(1, qtdVotes);
comand.executeUpdate();
comand.close();
conec.close();
}catch(SQLException e){
e.printStackTrace();
}
并将其推入1个元素。尝试直接推动状态:
scores
而且,有了数组函数,不需要componentDidMount() {
this.getRef().child('Western_Teams').on('child_added', (snapshot) => {
if (snapshot.exists()) {
// console.log(snapshot.val()) //val logs Object
// console.log(snapshot.key) //key logs city name
}
this.getRef().child('Western_Teams').once('child_added', (snapshot) => {
snapshot.forEach( (data) => {
let score = {
id: data.val().key
};
this.setState( (prevState) => ({
teamScore: [...prevState.teamScore, score]
}));
});
});
});
}
技巧。