【问题标题】:React - Add data to a listReact - 将数据添加到列表中
【发布时间】:2022-09-24 04:40:57
【问题描述】:

我有两个映射的项目列表。当我使用onClick={(e) => handleCheckClick(ele)} 单击div 时,我想在表格中显示单击的项目,但出现错误。

handleCheckClick函数

 function handleCheckClick(ele) {
 if (trayItems?.length > 0) {
     settrayItems(
       trayItems.map((item) => {
         return { ...item, quantity: item.quantity + 1 };
       })
     );
   } else {
     settrayItems([...trayItems, ele]);
   }
 }

我如何将两个列表项映射到div

<div>
{
    item && item.filter((person) => person.status == \"0\").map((ele) => {
        return (
            <div
                className=\"newmo-card\"
                style={styles.innerbox}
                onClick={(e) => handleCheckClick(ele)}>
                {`${ele.item}`}
                <br />
                <span> {`${ele.total_price}`}</span>
            </div>

        );
    })
}
</div>
<Tray trayItems2={trayItems} trayItems1={trayPrice} /> 

点击项目表:

  function Tray({ trayItems }) {
    return (
      <>
      <div className=\"foo\">
        <table>
          {trayItems &&
                trayItems.map((ele, index) => {
                  return (
                    <tr key={index}>
                      <td>{ele.item}</td>
                      <td>{ele.price}</td>
                      <td>{ele.quantity}</td>
                    </tr>
         
        </table>
      </div>
    </>
  );
}

检查sandbox,以便确定问题

  • 您必须提供您的错误。另外,您提供的代码丢失太多,例如,count 来自&lt;td&gt;{count}&lt;/td&gt; 并且缺少一些} 令牌。
  • 我已经更新了这个问题,实际上我没有 {count} 的逻辑,如果你能帮助解决这个问题会很好@HuyPham
  • 您也可以在这里分享您的商品数据。
  • [ { \"user_id\": 1, \"item\": \"biriani\", \"price\": \"50\", \"selling_price\": \"60\", \"created_at\ ": \"2022-08-29T10:12:58.000000Z\", \"updated_at\": \"2022-09-15T06:17:20.000000Z\", \"税\": \"5%\" , \"total_price\": \"80\", \"status\": 1 }, { \"user_id\": 5, \"item\": \"alfarm\", \"price\": \ "100\", \"sales_price\": \"120\", \"created_at\": \"2022-09-07T11:06:23.000000Z\", \"updated_at\": \"2022-09- 07T11:06:23.000000Z\", \"tax\": \"5%\", \"total_price\": \"140\", \"status\": 0 }, ]
  • @Kantivekariya 这是我在 console.log(item) 时得到的数据

标签: reactjs


【解决方案1】:

有一个警告&lt;td&gt; and &lt;tr&gt; cannot appear as a child of &lt;table&gt;

&lt;body&gt; 标签包裹body 并使用&lt;tr&gt; 标签来表示每一行。

<div className="foo">
  <table>
    <tbody>
      {trayItems2.length === trayItems1.length &&
        trayItems2.map((ele, index) => {
          return (
            <tr key={ele}>
              <td>{ele}</td>
              <td>{trayItems1[index]}</td>
            </tr>
          );
        })}
    </tbody>
  </table>
</div>

因为使用trayItems1[index] 来获取另一个数组中的地图项,所以您需要预先检查它们。您需要针对更严格的条件对其进行改进。

此外,为&lt;table&gt; 中的每个子元素定义唯一的键道具。这里我简单地使用key={ele}。并且使用两个数组是多余的。合并它们可能更容易。

【讨论】:

  • 它正在发生 bcz 你不能在你的 &lt;table&gt; 标签中添加 &lt;tbody&gt;
  • 谢谢,我错过了那部分。我已经更新了答案。
【解决方案2】:

在这里,您为什么要管理两个不同的状态?请检查工作演示here

import { Fragment, useState } from "react";
import "./styles.css";
const item = [
  {
    user_id: 1,
    item: "biriani",
    price: "50",
    selling_price: "60",
    created_at: "2022-08-29T10:12:58.000000Z",
    updated_at: "2022-09-15T06:17:20.000000Z",
    tax: "5%",
    total_price: "80",
    status: 1,
    quantity: 0

  },
  {
    user_id: 5,
    item: "alfarm",
    price: "100",
    selling_price: "120",
    created_at: "2022-09-07T11:06:23.000000Z",
    updated_at: "2022-09-07T11:06:23.000000Z",
    tax: "5%",
    total_price: "140",
    status: 0,
    quantity: 0
  }
];
export default function App() {
  const [trayItems, settrayItems] = useState([]);

  const handleCheckClick = (ele) => {
    if (trayItems?.length > 0) {
      settrayItems(trayItems.map((item) => {
        return { ...item, quantity: item.quantity + 1 };
      }))
    } else {
      settrayItems([...trayItems, ele]);
    }
  };

  function Tray({ trayItems }) {
    return (
      <>
        <div className="foo">
          <table>
            <tbody>
              {trayItems &&
                trayItems.map((ele, index) => {
                  return (
                    <tr key={index}>
                      <td>{ele.item}</td>
                      <td>{ele.price}</td>
                    </tr>
                  );
                })}
            </tbody>
          </table>
        </div>
      </>
    );
  }

  return (
    <>
      <div>
        {item &&
          item
            .filter((person) => person.status === 0)
            .map((ele, index) => {
              return (
                <div
                  key={index}
                  className="newmo-card"
                  onClick={() => handleCheckClick(ele)}
                >
                  {`${ele.item}`}
                  <br />
                  <span> {`${ele.total_price}`}</span>
                </div>
              );
            })}
      </div>
      <Tray trayItems={trayItems} />
    </>
  );
}


【讨论】:

  • 好的,但是当我单击超过 1 秒的项目时,可以说 biriani,我不希望再次添加它,我希望 birinani 的计数增加
  • 所以在这里你需要在 items 对象数组中添加数量字段。
  • 是的,你能帮我解释一下逻辑吗
  • 当然让我更新上面的代码。
  • @menucd 请检查我更新的增量逻辑
【解决方案3】:

我在这里分享代码的重要部分。检查代码沙箱中的工作代码。

以下是重大变化:

  1. Tray 定义移到App 组件之外。在另一个组件中定义一个组件几乎总是一个坏主意。您不会有任何问题,因为您在 Tray 中没有任何状态。如果你有任何状态,它会在每次渲染App 时重置为初始值。
  2. trayItems 更改为一个对象。键是每个项目的ids。值是一个包含名称、数量和价格的对象。
  3. 如果数量大于0,我们只会渲染Tray 中的项目。
  4. 更改了handleCheckClick 以处理对象。
    function Tray({ trayItems }) {
      return (
        <>
          <div className="foo">
            <table>
              <tbody>
                {Object.entries(trayItems)
                  .filter(([, v]) => v.quantity > 0)
                  .map(([k, v]) => {
                    return (
                      <tr key={k}>
                        <td>{v.item}</td>
                        <td>{v.price}</td>
                        <td>{v.quantity}</td>
                      </tr>
                    );
                  })}
              </tbody>
            </table>
          </div>
        </>
      );
    }
    
    export default function App() {
      const [trayItems, setTrayItems] = useState(
        item.reduce((prev, curr) => {
          return {
            ...prev,
            [curr.user_id]: { item: curr.item, quantity: 0, price: curr.price }
          };
        }, {})
      );
    
      const handleCheckClick = (ele) => {
        setTrayItems((prev) => {
          return {
            ...prev,
            [ele.user_id]: {
              ...prev[ele.user_id],
              quantity: prev[ele.user_id].quantity + 1
            }
          };
        });
      };
    
      return (
        <>
          <div>
            {item &&
              item
                .filter((person) => person.status === 0)
                .map((ele, index) => {
                  return (
                    <div
                      key={index}
                      className="newmo-card"
                      onClick={() => handleCheckClick(ele)}
                    >
                      {`${ele.item}`}
                      <br />
                      <span> {`${ele.total_price}`}</span>
                    </div>
                  );
                })}
          </div>
          <Tray trayItems={trayItems} />
        </>
      );
    

【讨论】:

    【解决方案4】:
    1. 方法(寻找)添加了以将 id 与托盘物品使用选择 id 的数组,如果相同则不生成 更改,但如果它不同,则创建一个新数组,这已完成 避免重复并添加ele。数量 = 1

    2. 创建了两个按钮,一个增加一个减少,都在增量法令函数的方法(地图)被添加,在 将 id 与选择的 id 进行比较的方法,如果是 相等,它被添加或减去,这取决于选择的 按钮,如果不是,仍然是相同的数字。

      https://codesandbox.io/s/fast-currying-nfmxfm?file=/src/App.js

        export default function App() {
            const [trayItems, settrayItems] = useState([]);
           
            const handleCheckClick = (ele) => {
              // 1.
              const dupe = trayItems.find((obj) => obj.user_id === ele.user_id);
              settrayItems(
                dupe
                  ? trayItems
                  : [...trayItems, { ...ele, quantity: (ele.quantity = 1) }]
              );
            };
         
        // 2.
        const incre = (idd) => {
          settrayItems(
            trayItems.map((stat) =>
              stat.user_id === idd ? { ...stat, quantity: stat.quantity + 1 } : stat
            )
          );
        };
      
        // 2.
        const decre = (idd) => {
          settrayItems(
            trayItems.map((stat) =>
              stat.user_id === idd
                ? {
                    ...stat,
                    quantity:
                      stat.quantity !== 1 ? stat.quantity - 1 : (stat.quantity = 1)
                  }
                : stat
            )
          );
        };
      
        function Tray({ trayItems }) {
          return (
            <>
              <div className="foo">
                <table>
                  <tbody>
                    {trayItems &&
                      trayItems.map((ele, index) => {
                        return (
                          <tr key={index}>
                            <td>{ele.item}</td>
                            <td>{ele.price}</td>
                            <td>{ele.quantity}</td>
                            <td>
                              <button onClick={() => incre(ele.user_id)}>+</button>
                              <button onClick={() => decre(ele.user_id)}>-</button>
                            </td>
                          </tr>
                        );
                      })}
                  </tbody>
                </table>
              </div>
            </>
          );
        }
      
        return (
          <>
            <div>
              {item &&
                item
                  .filter((person) => person.status === 0)
                  .map((ele, index) => {
                    return (
                      <div
                        style={{ cursor: "pointer" }}
                        key={index}
                        className="newmo-card"
                        onClick={() => handleCheckClick(ele)}
                      >
                        {`${ele.item}`}
                        <br />
                        <br />
                        <span> {`${ele.total_price}`}</span>
                      </div>
                    );
                  })}
            </div>
            <Tray trayItems={trayItems} />
          </>
        );
      }
      

    【讨论】:

      【解决方案5】:

      您的代码中有一些问题

      handleCheckClick函数

      const handleCheckClick = (ele) => {
      let index = trayItems.findIndex((item) => item.user_id === ele.user_id);
      if (index >= 0) {
        let newItems = trayItems;
        let item = trayItems.find((item) => item.user_id === ele.user_id);
        item = { ...item, quantity: item.quantity + 1 };
      
        newItems.splice(index, 1, item);
      
        settrayItems([...newItems]);
      } else {
        settrayItems([...trayItems, ele]);
      }
      };
      

      更多详情请查看sandbox

      【讨论】:

        【解决方案6】:

        您代码中的问题是您如何处理单击功能和随后的状态修改。

        1. 删除了重复的产品(具有相同的 id)
          const items = [
            {
              user_id: 1,
              item: "biriani",
              price: "50",
              selling_price: "60",
              created_at: "2022-08-29T10:12:58.000000Z",
              updated_at: "2022-09-15T14:05:45.000000Z",
              tax: "5%",
              total_price: "80",
              status: 0,
              quantity: 0
            },
            {
              user_id: 2,
              item: "burger",
              price: "80",
              selling_price: "80",
              created_at: "2022-08-29T10:21:13.000000Z",
              updated_at: "2022-09-14T04:46:36.000000Z",
              tax: "5%",
              total_price: "100",
              status: 0,
              quantity: 0
            },
            {
              user_id: 3,
              item: "alfarm",
              price: "100",
              selling_price: "120",
              created_at: "2022-09-07T11:06:23.000000Z",
              updated_at: "2022-09-07T11:06:23.000000Z",
              tax: "5%",
              total_price: "140",
              status: 0,
              quantity: 0
            },
            {
              user_id: 4,
              item: "sandwich",
              price: "100",
              selling_price: "120",
              created_at: "2022-09-07T13:27:33.000000Z",
              updated_at: "2022-09-14T04:46:37.000000Z",
              tax: "5",
              total_price: "140",
              status: 0,
              quantity: 0
            },
            {
              user_id: 5,
              item: "pizza",
              price: "200",
              selling_price: "220",
              created_at: "2022-09-07T13:27:33.000000Z",
              updated_at: "2022-09-07T13:27:33.000000Z",
              tax: "5",
              total_price: "240",
              status: 0,
              quantity: 0
            },
            {
              user_id: 6,
              item: "chicken sadwich",
              price: "200",
              selling_price: "220",
              created_at: "2022-09-07T13:27:33.000000Z",
              updated_at: "2022-09-07T13:27:33.000000Z",
              tax: "5",
              total_price: "250",
              status: 0,
              quantity: 0
            },
            {
              user_id: 7,
              item: "sharja shake",
              price: "60",
              selling_price: "70",
              created_at: "2022-09-09T06:58:45.000000Z",
              updated_at: "2022-09-15T14:05:53.000000Z",
              tax: "5%",
              total_price: "80",
              status: 0,
              quantity: 0
            }
          ];
          
          1. 为产品保留单个变量并相应更新状态
          export default function App() {
            const [trayItems, setTrayItems] = useState([]);
          
            const handleCheckClick = (item) => {
              const itemExists = trayItems.findIndex((ite) => ite.user_id === item.user_id) !== -1;
              if (itemExists) {
                setTrayItems(
                  trayItems.map((prod) => ({
                    ...prod,
                    quantity:
                      prod.user_id === item.user_id ? prod.quantity + 1 : prod.quantity
                  }))
                );
              } else {
                setTrayItems([...trayItems, { ...item, quantity: item.quantity + 1 }]);
              }
            };
          
            return (
              <>
                <table>
                  {items
                    ?.filter((item) => item.status === 0)
                    ?.map((item, index) => {
                      return (
                        <tbody
                          key={index}
                          onClick={() => handleCheckClick(item)}
                        >
                          <td>{item.item}</td>
                          <td>{item.total_price}</td>
                        </tbody>
                      );
                    })}
                </table>
                <Tray trayItems={trayItems} />
              </>
            );
          }
          
          1. 将子组件移到父组件之外。
          const Tray = ({ trayItems }) => {
            return (
              <table>
                <tbody>
                    {trayItems?.map((ele, index) => (
                      <tr key={index}>
                        <td>{ele.item}</td>
                        <td>{ele.price}</td>
                        <td>{ele.quantity}</td>
                      </tr>
                    ))}
                </tbody>
              </table>
            );
          };
          
          

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-10-31
          • 2018-09-08
          • 1970-01-01
          • 1970-01-01
          • 2013-09-01
          • 2019-06-23
          • 1970-01-01
          • 2021-02-19
          相关资源
          最近更新 更多