Solidity

Truffle - Solidity Mapping 無法通過 JS 訪問

  • April 10, 2022

再會,

我目前是 Solidity 開發的新手,希望你能幫助我。

我有這份契約,上面寫著:

contract Shop {
 struct Item {
   string name;
   string description;
   address tAddress;
   uint256 price;
   bool isHidden;
 }

 address public owner;

 mapping(address => Item) public items;

 constructor() public {
   owner=msg.sender;

   items[owner].price = 0.00;
   items[owner].description = "";
   items[owner].name = "";
 }

 // Adding an item
 function addItem(uint256 price, string memory name, string memory description) public returns (Item memory) {
   items[owner].price = price;
   items[owner].description = description;
   items[owner].name = name;
   items[owner].tAddress = owner;
   items[owner].isHidden = true;

   return (items[owner]);
 }

 // Retrieving the items
 function getItem(address _key) public returns (Item memory) {
   Item memory item = items[owner];
   return item;
 }
}

我可以獲得 addItem 的正確回報,但在 getItem 方法上,它似乎不會響應正確的值。

我確實得到了這個回報:

獲取項目返回

任何幫助是極大的讚賞。

謝謝!

編輯:

這是JS程式碼:

 state = { storageValue: 0, web3: null, accounts: null, contract: null };

 componentDidMount = async () => {
   try {
     // Get network provider and web3 instance.
     const web3 = await getWeb3();

     // Use web3 to get the user's accounts.
     const accounts = await web3.eth.getAccounts();

     // Get the contract instance.
     const networkId = await web3.eth.net.getId();
     const deployedNetwork = Shop.networks[networkId];

     console.log(" deployedNetwork ");
     console.log(deployedNetwork);
     console.log(Shop);

     const instance = new web3.eth.Contract(
       Shop.abi,
       deployedNetwork && deployedNetwork.address,
     );

     // Set web3, accounts, and contract to the state, and then proceed with an
     // example of interacting with the contract's methods.
     this.setState({ web3, accounts, contract: instance }, this.runExample);
   } catch (error) {
     // Catch any errors for any of the above operations.
     alert(
       `Failed to load web3, accounts, or contract. Check console for details.`,
     );
     console.error(error);
   }
 };

 runExample = async () => {
   const { accounts, contract } = this.state;
   const sender = await contract.methods.showSender.call();

   console.log(" sender ");
   console.log(sender);

   shopItems.map(async (item) => {
     const addedItem = await contract.methods.addItem(item.price, item.name, item.description).call();

     console.log(addedItem);
   })

   // Get the value from the contract to prove it worked.
   console.log(" account ");
   console.log(accounts[0]);

   const response = await contract.methods.getItem(accounts[0]).call();

   console.log(" response ");
   console.log(response);
   // Update state with the result.
   // this.setState({ storageValue: response });
 };

使用 send 而不是 call 來更新鏈內的變數。

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