Solidity

使用 web3.js 在映射中訪問結構內的數組

  • May 31, 2020

我創建了一個結構病人如下,以及一個 uint->patient 的映射。

struct patient {
   uint pId;
   string name;
   string phone;
   address payable owner;
   uint numRecords;
   uint[] cost;
   address[] uploader;
   string[] procedure;
   uint[] hospId;
   string[] doctorName;
   bool[] treated;
   string[] image;

}


mapping(uint => patient) public patients;

我已經創建了將數據插入映射的函式。但是,當我嘗試使用 web3 讀取 reactjs 中的數據時,

//REACTJS     
for (var i = 1; i <= patientCount; i++) {                                                 
           const patient = await container.methods.patients(i).call()
   }

患者變數僅包含結構的非數組部分。即,只返回 pId、name、phone、owner 和 numRecords。

返回的值為

{0: BigNumber, 1: "Name", 2: "1234567890", 3: "0x771D3a7C2d6C59D9030731a48D60D8296303fC06", 4: BigNumber, pId: BigNumber, name: "Name", phone: "1234567890", owner: "0x771D3a7C2d6C59D9030731a48D60D8296303fC06", numRecords: BigNumber}
0: BigNumber {_hex: "0x01", _ethersType: "BigNumber"}
1: "NAme"
2: "1234567890"
3: "0x771D3a7C2d6C59D9030731a48D60D8296303fC06"
4: BigNumber {_hex: "0x01", _ethersType: "BigNumber"}
name: "Name"
numRecords: BigNumber {_hex: "0x01", _ethersType: "BigNumber"}
owner: "0x771D3a7C2d6C59D9030731a48D60D8296303fC06"
pId: BigNumber {_hex: "0x01", _ethersType: "BigNumber"}
phone: "1234567890"
__proto__: Object

為了返回整個結構,您需要使用 ABIEncoderV2 並定義您自己的 getter 函式

pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;

contract Foo {

 function getPatient(uint id) public view returns (patient memory) {
   return patients[id];
 }
}

引用自:https://ethereum.stackexchange.com/questions/83883