我想在我的Web应用程序中调用这段React JS代码。事实是,尽管我尝试在render()
方法中调用它,但这导致了无限循环。然后,我尝试在constructor()
内调用它,并调用componentWillUpdate()
,但未在其中触发函数。
listenForNewPins() {
console.log("listening for new segnalazioni...");
var ref = firebase.database().ref("segnalazioni");
ref.on("child_added", function(snapshot) {
console.log("new value under segnalazioni:");
console.log("fetched:", snapshot.val());
console.log("---------------------------------");
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
if (typeof childData.luogo === "undefined") {
console.log("undefined, ignoring...");
} else {
console.log("Using child data:", childData);
this.setState({ markers: [...this.state.markers, childData] });
}
});
});
}
这是完整的组件:
import React from "react";
import CustomMap from "./components/CustomMap";
import NavBar from "./components/NavBar";
import firebase from "./Firebase";
export default class App extends React.Component {
state = {
markers: []
};
constructor() {
super();
this.listenForNewPins();
}
listenForNewPins() {
console.log("listening for new segnalazioni...");
var ref = firebase.database().ref("segnalazioni");
ref.on("child_added", function(snapshot) {
console.log("new value under segnalazioni:");
console.log("fetched:", snapshot.val());
console.log("---------------------------------");
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
if (typeof childData.luogo === "undefined") {
console.log("undefined, ignoring...");
} else {
console.log("Using child data:", childData);
this.setState({ markers: [...this.state.markers, childData] });
}
});
});
}
render() {
const { markers } = this.state;
return (
<div>
<NavBar />
<CustomMap markers={markers} />
</div>
);
}
}
有任何提示吗?