首页 > 解决方案 > Solidity 函数将空数组返回给 web3.js

问题描述

Solidity 函数在 Remix 和 truffle 控制台上执行时返回一个字符串数组,而从 JS 调用时它返回一个空数组

坚固性代码

mapping(address => string[]) addressLink;
function getLinks(address a) public view returns (string[] memory)
  {
    return addressLink[a];
  }

JS代码

contract.methods.getLinks(accounts[0]).call().then(res => {
                 console.log(res)
             });

从 JS 调用时的松露控制台结果和预期结果

[ 'QmTiMLN8X4NE4ho5mqJ9t4bJ17JxfMHAFcg3z66f8vdUh1' ]

浏览器控制台上的结果(实际结果)

[""]
0: ""
length: 1

标签: javascriptsolidityweb3

解决方案


您可能在 javascript 代码中设置了错误的合约地址:

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

第二个参数为合约地址,见:https ://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#new-contract

希望能帮助到你。


推荐阅读