React中使用axios获取订单数组后如何提取所有userId字段
问题根因
你调用orders接口返回的res.data是订单数组,数组本身没有userId属性,只有数组内的单个订单元素才挂载该字段,所以直接打印res.data?.userId必然返回undefined,只有通过下标指定具体订单元素才能正常取值。
打印所有userId的方法
直接遍历订单数组即可输出所有userId:
res.data.forEach(order => console.log(order.userId))
实现订单列表展示用户名的方案
你当前已经请求了全量用户列表,我们可以把用户数组转换为userId对应用户名的映射对象,渲染时直接匹配取值即可,修改后的完整代码如下:
import React, { useEffect, useState, useMemo } 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([]) // 生成userId到用户名的映射表,避免每次渲染重复遍历 const userMap = useMemo(() => { return users.reduce((map, user) => { map[user._id] = user.username // 字段名如果和你接口实际返回的不一致可以自行调整 return map }, {}) }, [users]) useEffect(() => { const getOrders = async () => { //this is just a shorcut api try { const res = await userRequest.get('orders') setOrders(res.data) // 打印所有userId res.data.forEach(order => console.log(order.userId)) } catch (error) { console.log(error) } } getOrders() }, []) useEffect(() => { const getUsername = async () => { try { const res = await userRequest.get('user/find/') setUsers(res.data) } catch (error) { console.log(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" key={order._id}> {/* 加key避免React警告 */} <td className="widgetLgUser"> <span className="WidgetLgName"> {userMap[order.userId] || '未知用户'} </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
补充说明
如果你的user/find/接口不支持返回全量用户,需要传单个userId查询,那可以在拿到订单列表后提取所有userId批量请求用户信息,再存入映射表即可。
内容的提问来源于stack exchange,提问作者s_sldiblood
相关产品推荐
相关产品推荐

