首页 > 解决方案 > 数组 map() 检索旧项目

问题描述

据我所知,The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.我有一个对象数组。我想渲染每个项目并且它工作正常!这是我正在使用的代码->

<div className="itemsSection__items">
      {items &&
        items.map((item) => {
          return (
            <Item
              key={Math.random()}
              imageUrl={item.image}
              userName={item.userName}
            />
          );
        })}
    </div>

但是在项目被渲染后,我试图安慰items. 但它只给了我一个空数组([])。那么,即使在map函数之后,我怎样才能检索项目?

编辑:

 socket.on("connect", () => {
    console.log("connected");
  });

  socket.on("newItem", (item) => {
    const newItem = JSON.parse(item);
    console.log(items)
  });

在这里,当我尝试安慰这些项目时,它是一个空数组!

谢谢 !

标签: javascriptarraysreactjs

解决方案


推荐阅读