微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过它映射时无法获取整个产品列表,仅获取组件中列表中最后添加的项目

如何解决通过它映射时无法获取整个产品列表,仅获取组件中列表中最后添加的项目

我正在开发一个市场 DApp,卖家可以在其中列出待售产品,而买家可以使用以太币购买。我使用 Metamask 作为钱包,使用 ganche 作为我本地运行的区块链。

当卖家添加待售产品时,它会显示在购买组件中供买家购买,但随着再添加一件待售产品,购买组件只会显示最新添加的待售产品,而不是所有产品。

我正在使用 map 函数来映射产品数组,以下是返回买方组件的代码

<tbody id="productList">
   { productList.map((product,key) => {
      return(
        <tr key={key}>
        <th scope="row">{ product.id.toString()}</th>
        <td>{product.name}</td>
        <td>{window.web3.utils.fromWei(product.price.toString(),'Ether')} ETH</td>
        <td>{product.owner}</td>
        <td>
          { !product.purchased
            ? <button className="btn btn-primary"
                  name={product.id}
                  value={product.price}
                  onClick{purchaseProduct(e.target.name,e.target.value)                                                            }}                                                       >Buy
              </button>
            : <button className="btn btn-success">Owned</button>
          }
         </td>
         </tr>
       );
     })}
</tbody>

productList 是包含从 App.jsloadBlockchainData 函数传递下来的产品列表的状态,我们连接到智能合约并定义 productList:

const [loading,setLoading] = useState(true);  
const [account,setAccount] = useState("");
const [marketplace,setMarketplace] = useState("");
const [productList,setProducts] = useState([]);


const loadBlockchainData = async () => {
    const web3 = window.web3;

    const accounts = await web3.eth.getAccounts();

    setAccount(accounts[0]);
    const networkId = await web3.eth.net.getId();
    const networkData = Marketplace.networks[networkId]
    if (networkData) {
      const marketplace = new web3.eth.Contract(Marketplace.abi,networkData.address);
      // console.log(marketplace);
      setMarketplace(marketplace);
      const productCount = await marketplace.methods.productCount().call();
      // console.log(productCount.toString());
      setProductCount(productCount);
      for (var i = 1; i <= productCount; i++) {
        const product = await marketplace.methods.products(i).call();
        setProducts([...productList,product]);
        console.log(productList);

      }
      setLoading(false);
    } else {
      window.alert("Marketplace contract not deployed to detected network.");
      // setloading2(true);
    }
  };

另外,点击购买按钮后需要手动刷新页面,将Buy按钮改为Owned,状态不会自动更新,如何实现。

感谢您回答这么长的问题,但任何帮助将不胜感激。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?