React-Bootstrap-Table2不显示Firebase中的数据 [英] React-bootstrap-table2 doesn't show data from Firebase
问题描述
我一直在尝试从Firebase实时数据库检索数据并将其显示在react-bootstrap-table2中,但是在实际显示数据时遇到了一些问题.当我运行代码时,表中未打印任何值,但是,控制台中没有错误.如果我将表中显示的值的数量设置为25,则会发生错误:Uncaught TypeError:无法读取未定义的属性"timestamp".但是,如果我使用console.log时间戳记,则首先会得到一个空数组,然后是一个带有时间戳记的值的数组(请参见下面的屏幕截图).
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).
这是我的代码:
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;
有人知道为什么我的版本不起作用吗?任何帮助将不胜感激!
Does anyone know why my version doesn't work? Any help would be appreciated!
推荐答案
由于您正在使用功能组件,因此请使用挂钩来设置状态,这将在设置状态后重新呈现组件:
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;
这篇关于React-Bootstrap-Table2不显示Firebase中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!