【问题标题】:How can I fetch the user information by getting it from the order userId如何通过从订单 userId 获取用户信息来获取用户信息
【发布时间】:2022-01-10 12:45:47
【问题描述】:

如何通过userId获取客户信息?我尝试创建另一个 useEffect,但它不起作用,如果我已经使用 orders.map(),我无法将其映射到部门上

import { useEffect, useState } from "react";
import { userRequest } from "../../requestMethod";
import "./widgetLg.css";

export default function WidgetLg() {
  const Button = ({ type }) => {
    return <button className={"widgetLgButton " + type}>{type}</button>;
  };

  const [orders, setOrders] = useState([])

  useEffect(() => {
    const getOrders = async () => {
      try {
        const res = await userRequest.get("orders");
        setOrders(res.data)
        const userInfo = await userRequest.get("user/find/61ab2c6826a0dd9359e185e0")
    ///    console.log(userInfo.data)

      } catch {
        console.log("Error")
      }
    };
    getOrders();
  }, []);

  useEffect(() =>{
    const getUserInfo = async () =>{
      try {
        const userInfo = await userRequest.get('user/find/'+orders._id)
      } catch (error) {
        
      }
    }
    getUserInfo()
  },[])
  
  return (
    
    <div className="widgetLg">
      <h3 className="widgetLgTitle">Latest transactions</h3>
      <table className="widgetLgTable">
        <tbody>

        <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}>
          <td className="widgetLgUser">
            <img
              src="https://images.pexels.com/photos/4172933/pexels-photo-4172933.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
              alt=""
              className="widgetLgImg"
              />
            <span className="widgetLgName"> Username </span>
          </td>
          <td className="widgetLgDate">{order.createdAt}</td>
          <td className="widgetLgAmount">${order.amount}</td>
          <td className="widgetLgStatus">
            <Button type={order.status} />
          </td>
        </tr>
              ))}
        </tbody>

      </table>
    </div>
  );
}

对不起,我不太擅长用英语解释。我试图裁剪它并画一条线以进一步可视化它。感谢您的帮助

【问题讨论】:

  • 那么你想从你的订单中获取所有的userIds并使用它们从服务器获取数据?
  • 是的,@kianjalilian。然后我将渲染数据并抓取用户名并将其显示给最新的交易

标签: reactjs mongodb object axios mern


【解决方案1】:

您可以像这样获取所有 userId 的数组:

 const userIds = orders.map(order => order.userId);

如果您想要 userIds 中所有用户的用户信息,则不应单独发送请求,因为您的应用程序会遇到较长的延迟和响应时间。

我建议您在后端编写一个 api,该 API 采用 userIds 数组并立即返回所有这些用户的数据,或者如果您只需要用户名,则在您的订单中填充用户的用户名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-03
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 2011-10-31
    • 2018-05-21
    相关资源
    最近更新 更多