首页 > 解决方案 > 如何获取特定 API 列的值

问题描述

我正在创建一个电子商务网站,我正在尝试使用外键或我的表的第二列(即userID使用 Axios GET 请求)获取某个购物车。这是我的表结构

cartID | userID | | productName
1          1            chair
2          3            ....
3          3            ....

如何显示唯一userID的数据3

因为我不能这样做 axios.get("https://localhost:3000/api/carts/cartID/userID/3")

这就是我获取数据的方式

const [myCart, setMyCart] = useState([])

useEffect(() => {
    axios
      .get("https://localhost:3000/api/carts/")
      .then((res) => {
        setMyCart(res.data)
        console.log(res.data)
      })
  }, []);

这就是我显示数据的方式

{myCart.map((item, index) => {
              return(
              <tr key={index.id}>
                  <td >{index + 1}</td>
                  <td>{item.name}</td>
              </tr>
  )}
)}

标签: reactjsapiaxios

解决方案


您可以使用这样的条件:

{
  myCart.map((item, index) => {
    if (item.id === 3) {
      return (
        <tr key={index.id}>
          <td>{index + 1}</td>
          <td>{item.name}</td>
        </tr>
      );
    }

    return null;
  });
}

推荐阅读