今天剛接觸這塊,弄了個小的例子做了下測驗,遇到如下問題:
留言資訊無法push到結構體陣列里。 Message[] public Messagelist; Messagelist 的長度始終為0
合約代碼如下:
pragma solidity >=0.4.21 <0.7.0;
import "./ConvertLib.sol";
contract MetaCoin {
struct Message {
string title;
address from;
}
Message[] public Messagelist;
function SetMsg(string memory titles) public {
Message memory msg = Message(titles,msg.sender);
Messagelist.push(msg );
}
function getMsg(uint random) public view returns (uint, string memory, address) {
if(Messagelist.length==0){
return (Messagelist.length, "", msg.sender);
}else{
Message storage result = Messagelist[random];
return (Messagelist.length, result.title, result.from);
}
}
}
前端js代碼如下:
SetMsg: async function (str) {
const { SetMsg } = this.meta.methods;
const testinfo = await SetMsg(str).call();
console.info("Set", testinfo);
},
GetMsg: async function (num) {
const { getMsg } = this.meta.methods;
const testinfo = await getMsg(num).call();
console.info("Get:", testinfo);
}
先呼叫 SetMsg 傳入字符 進行寫操作。再呼叫 GetMsg 通過傳入數字(陣列下標)取值,奇怪的是總是執行 合約里的 if(Messagelist.length==0){ 這句,也就是狀態變數無法保存資料。
另外:這段代碼我remix 上測驗是沒問題的。
我開發環境:truffle+ganache
哪位大佬幫指點一下到底問題出在哪兒。謝謝。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/191160.html
標籤:區塊鏈技術
