我有一个反应应用程序。在驱动程序页面组件(DriverWay)中,我从数据库接收所有订单并将它们写入orderList。我试图通过 Order 组件在屏幕上显示数据,但它不起作用。数组不为空,我检查过
驾驶方式:
const orderList = [];
const DriverWay = () => {
const listen = onAuthStateChanged(auth, (user) => {
if (user) {
setUid(user.email.split('@')[0]);
}
});
const db = getDatabase();
const dbRef = ref(db, 'orders/');
function handleOnClick() {
onValue(
dbRef,
(snapshot) => {
snapshot.forEach((childSnapshot) => {
orderList.push(childSnapshot.val());
});
},
{
onlyOnce: true,
}
);
}
handleOnClick();
orderList.map((item) => console.log(item));
return (
<div className={styles.driver__way__block}>
<MapWithRoute />
<Button
type="submit"
onClick={handleOnClick}
width={19.9375}
height={3.6875}
bgc="FFE500"
btnText="Показать заказы"
btnTextColor="FFF"
/>
<div
style={{
position: 'absolute',
width: '100vw',
height: '100vh',
zIndex: 9999999,
backgroundColor: '#fff',
top: 0,
}}
>
{orderList.map((order) => (
<Order
key={order}
nowGeo={order.nowGeolocation}
endGeo={order.endGeolocation}
uid={order.uid}
/>
))}
</div>
</div>
);
};
命令:
const Order = (props) => {
return (
<div>
<h1>Now geo: {props.nowGeo}</h1>
<h2>End geo: {props.endGeo}</h2>
</div>
);
};
export default Order;
应用程序.jsx:
function App() {
return (
<div className="App">
<Routes>
<Route path="/driver-way" element={<DriverWay uid={driverId} />} />
</Routes>
</div>
);
}
export default App;
我错过了接收数据和记录的机会。我还尝试使用简单地显示数组的元素.map (orderList.map((item) => console.log(item));)
。日志为空,屏幕上没有任何内容
据我所知你没有使用 State
使用State让组件在数组变化时更新
执行请求时,需要调用setOrderlist(New Array),使组件重新渲染
使用 useEffect 一次性更新组件:
在函数内部编写 fetch 和 setOrderList 来获取状态
**编辑
将这段代码放在App.jsx中:
将 orderList 作为 props 传递给 DriverWay
你的 orderList 应该是一个组件状态变量,以便 React 可以跟踪更改并重绘页面上的数据。
另外,最好从组件中删除与数据库(或其他任何内容)的连接的初始化,否则组件内的每个数据更改都将启动一个新连接。
另外,调用
handleOnClick
组件内部的函数会导致再次请求数据,再次调用函数,然后整个事情就会陷入循环。