问题
I've been trying to retrieve data from Firebase Realtime Database and display it in a react-bootstrap-table2, but I've run into some issues when it comes to actually displaying the data. When I run the code no value is printed into the table, however, there is no error in console. If I set the number of displayed values in the table to 25, an error occurs: Uncaught TypeError: Cannot read property 'timestamp' of undefined. However, if I console.log timestamp I first get an empty array and then an array with the timestamped values (see the screenshot below).
Here is my code:
const App = () => {
const timestamp = [];
const getTimestamp = () => {
const database = db.ref().child("timestamped_measures");
database.on("value", (ts_measures) => {
ts_measures.forEach((ts_measure) => {
const array = {
time: ts_measure.val().timestamp,
};
timestamp.push(array);
});
});
};
const columns = [{ dataField: "time", text: "Timestamp" }];
useEffect(() => {
getTimestamp();
}, []);
console.log(timestamp);
return (
<div className="App">
<BootstrapTable
keyField="timestamp"
data={timestamp}
columns={columns}
pagination={paginationFactory()}
/>
</div>
);
};
export default App;
This is what my Firebase database looks like
This is what my page and console look like
When the pagination is set from 10 to 25, this is what the error looks like
Does anyone know why my version doesn't work? Any help would be appreciated!
回答1:
Since you are using functional component so make use of hooks for setting state, this will re-render your component after setting your state:
const App = () => {
// Make timestamp state
const {timestampList, setTimestampList} = React.useState([]);
const timestamp = [];
const getTimestamp = () => {
const database = db.ref().child("timestamped_measures");
database.on("value", (ts_measures) => {
ts_measures.forEach((ts_measure) => {
const array = {
time: ts_measure.val().timestamp,
};
timestamp.push(array);
});
// Set array to timestamp state array
setTimestampList(timestamp);
});
};
const columns = [{ dataField: "time", text: "Timestamp" }];
useEffect(() => {
getTimestamp();
}, []);
console.log(timestamp);
return (
<div className="App">
<BootstrapTable
keyField="timestamp"
data={timestampList} // Pass timestamp state to data prop
columns={columns}
pagination={paginationFactory()}
/>
</div>
);
};
export default App;
来源:https://stackoverflow.com/questions/63261651/react-bootstrap-table2-doesnt-show-data-from-firebase