记录数组中每个元素的一个字段



我在数据库中有对象。我想使用axios获取userId,但当我尝试console.log((时,它显示为未定义。当我对它进行硬编码并以数组为目标时,它显示了。

如何对所有userId进行控制台日志记录?我想获取它,这样我就可以将它用作我的数据库的端点

const-res=wait userRequest.get('user/find/'+userId(

我只想获取userId。

import React, { useEffect, useState } from 'react'
import { format } from 'timeago.js'
import { userRequest } from '../../requestMethod'
import './Widgetlg.css'
const WidgetLg = () => {
const Button = ({ type }) => {
return <button className={'widgetLgButton ' + type}>{type}</button>
}
const [orders, setOrders] = useState([])
const [users, setUsers] = useState([])
useEffect(() => {
const getOrders = async () => {
//this is just a shorcut api
try {
const res = await userRequest.get('orders')
setOrders(res.data)
console.log(res.data?.userId)
console.log(res.data)
console.log(res.data[0].userId)
} catch (error) {
console.log(error)
}
}
getOrders()
}, [])
useEffect(() => {
const getUsername = async () => {
try {
const res = await userRequest.get('user/find/')
setUsers(res.data)
} catch (error) {}
}
getUsername()
}, [])
return (
<div className="widgetLg">
<h3 className="widgetLgTitle">Latest Transactions</h3>
<table className="widgetTable">
<tr className="widgetLgTr">
<th className="widgetLgTh">Customer</th>
<th className="widgetLgTh">Date</th>
<th className="widgetLgTh">Amount</th>
<th className="widgetLgTh">Status</th>
</tr>
{orders.map((order) => (
<tr className="widgetLgTr">
<td className="widgetLgUser">
<span className="WidgetLgName"> **I want here to show the username** </span>
</td>
<td className="widgetLgDate"> {format(order.createdAt)} </td>
<td className="widgetLgAmmount">P {order.amount} </td>
<td className="widgetLgStatus">
<Button type={order.status} />
</td>
</tr>
))}
</table>
</div>
)
}
export default WidgetLg

如果我正确理解你的,你可以尝试这样的东西

const userIdsArray = res.data.map(d => d.userId);
console.log(userIdsArray);

res.data是一个数组。要记录所有元素,只需对它们进行迭代:

res.data.forEach(el => console.log(el.userId));

console.log(res.data)给出undefined的原因是数组本身没有userId字段,只有数组的元素有。

最新更新