React JS如何将其转换为组件?

发布于 2025-02-07 18:37:29 字数 2073 浏览 0 评论 0原文

const ItemList = () => {

    fetch('http://localhost:3001/api/itemList/', {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
        body: JSON.stringify({
            userId: localStorage.getItem("userId"),
        })
    }).then(res => res.json())

        .then(data => {
            data = data.map(item => {
                console.log(item);
                return (
                    document.getElementById('cards').innerHTML +=
                    `<div class="card" style="width: 18rem;">
                    <img src="${item.imagePath}" class="card-img-top" alt="..." />
                    <div class="card-body">
                        <h5 class="card-title">${item.itemName}</h5>
                        <p class="card-text">${item.tag}</p>
                    </div>
                </div>`

              

我有一个数据将卡推到前面的数据。我刚刚找到了与卡一起使用的方式,但我想使用卡组件使其变得更好。

如果我将innerhtml零件转换为:

                return (
                    document.getElementById('cards').innerHTML +=
                    <Card style={{ width: '18rem' }}>
                        <Card.Img variant="top" src={item.imagePath} />
                        <Card.Body>
                            <Card.Title>{item.itemName}</Card.Title>
                            <Card.Text>
                                {item.tag}
                            </Card.Text>
                        </Card.Body>
                    </Card>
                )

我正在作为输出

[对象对象] [对象对象] [对象对象] [对象对象]

我在哪里犯错?我该如何推动使用卡片来领先这些JSON数据?

示例JSON数据


{ "id": 1, "itemName": "sadasd", "itemImagePath": "pngwing.com.png", "userID": "117961395738439786389", "tags": [ "tags", "ts" ], "createdAt": "2022-06-15T00:27:42.958Z", "updatedAt": "2022-06-15T00:27:42.958Z" }

const ItemList = () => {

    fetch('http://localhost:3001/api/itemList/', {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
        body: JSON.stringify({
            userId: localStorage.getItem("userId"),
        })
    }).then(res => res.json())

        .then(data => {
            data = data.map(item => {
                console.log(item);
                return (
                    document.getElementById('cards').innerHTML +=
                    `<div class="card" style="width: 18rem;">
                    <img src="${item.imagePath}" class="card-img-top" alt="..." />
                    <div class="card-body">
                        <h5 class="card-title">${item.itemName}</h5>
                        <p class="card-text">${item.tag}</p>
                    </div>
                </div>`

              

I have a data for push to front with cards. I just found this way works with cards but I want to use Cards component for make it better.

If I convert innerHTML part to that:

                return (
                    document.getElementById('cards').innerHTML +=
                    <Card style={{ width: '18rem' }}>
                        <Card.Img variant="top" src={item.imagePath} />
                        <Card.Body>
                            <Card.Title>{item.itemName}</Card.Title>
                            <Card.Text>
                                {item.tag}
                            </Card.Text>
                        </Card.Body>
                    </Card>
                )

I am getting as a output

[object Object][object Object][object Object][object Object]

Where I am making mistake? and how can I push to front this json data with cards?

Example json data


{ "id": 1, "itemName": "sadasd", "itemImagePath": "pngwing.com.png", "userID": "117961395738439786389", "tags": [ "tags", "ts" ], "createdAt": "2022-06-15T00:27:42.958Z", "updatedAt": "2022-06-15T00:27:42.958Z" }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷荒 2025-02-14 18:37:29

只需删除document.getElementById('cards')。innerhtml +=。你不想要那个。 ReactJS应进行DOM更新。而且,您不应从fetch函数返回。创建一个状态,您可以使用它来渲染jsx ..这是适合您的功能组件

import { useEffect, useState } from "react";

const ItemList = () => {
  const [item, setItem] = useState({});

  useEffect(() => {
    fetch("http://localhost:3001/api/itemList/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        userId: localStorage.getItem("userId"),
      }),
    })
      .then((res) => res.json())
      .then((data) => {
        setItem(data);
      });
  }, []);

  return (
    <>
      {item && Object.keys(item).length > 0 && (
        <Card style={{ width: "18rem" }}>
          <Card.Img variant="top" src={item.imagePath} />
          <Card.Body>
            <Card.Title>{item.itemName}</Card.Title>
            <Card.Text>{item.tag}</Card.Text>
          </Card.Body>
        </Card>
      )}
    </>
  );
};

export default ItemList;

在这里,我使用使用效果挂钩在dom上安装组件时获取项目。我们正在验证item对象在渲染之前不是空的

Just remove the document.getElementById('cards').innerHTML +=. You don't want that. ReactJS should do the DOM update. And, you should not return from the fetch function. Create a state, and you can use it to render the JSX.. Here is the properly structured Functional Component for you.

import { useEffect, useState } from "react";

const ItemList = () => {
  const [item, setItem] = useState({});

  useEffect(() => {
    fetch("http://localhost:3001/api/itemList/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        userId: localStorage.getItem("userId"),
      }),
    })
      .then((res) => res.json())
      .then((data) => {
        setItem(data);
      });
  }, []);

  return (
    <>
      {item && Object.keys(item).length > 0 && (
        <Card style={{ width: "18rem" }}>
          <Card.Img variant="top" src={item.imagePath} />
          <Card.Body>
            <Card.Title>{item.itemName}</Card.Title>
            <Card.Text>{item.tag}</Card.Text>
          </Card.Body>
        </Card>
      )}
    </>
  );
};

export default ItemList;

Here, I used the useEffect hook to fetch the items when the component is mounted on DOM. And we are verifying if the item object is not empty before rendering

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文