簡體   English   中英

對象作為 React 子級無效。 如果您打算渲染一組子項,請改用數組 - 錯誤 Solidity - React

[英]Objects are not valid as a React child. If you meant to render a collection of children, use an array instead - Error Solidity - React

我正在開發一個帶有 ReactJS 和solidity - 智能合約的文檔驗證系統。 我想在前端顯示我的智能合約的get().call()方法的結果,帶有彈出窗口甚至是簡單的文本。 我現在面臨的問題是,當我嘗試顯示該方法的響應時,它會向我拋出該錯誤:

對象作為 React 子級無效。 如果您打算渲染一組孩子,請改用數組

這是我的solidity合約的代碼:

pragma solidity ^0.5.0;
contract Proof1 {
  struct FileDetails {
    uint256 timestamp;
    string owner;
  }
  mapping(string => FileDetails) files;
  event logFileAddedStatus(
    bool status,
    uint256 timestamp,
    string owner,
    string fileHash
);

function set(string memory owner, string memory fileHash) public {
  if (files[fileHash].timestamp == 0) {
    files[fileHash] = FileDetails(block.timestamp, owner);

    emit logFileAddedStatus(true, block.timestamp, owner, fileHash);
  } else {
    emit logFileAddedStatus(false, block.timestamp, owner, fileHash);
  }
}

function get(string memory fileHash)
public
view
returns (uint256 timestamp, string memory owner)
{
  return (files[fileHash].timestamp, files[fileHash].owner);
}}

這是 onClick 方法中的.get().call()方法:

onSubmitGet = async (event) => {
  event.preventDefault();
  const hash = document.getElementById("hash").value;

  this.state.design = await this.state.contract.methods
    .get(hash)
    .call({ from: this.state.address })
    .then((res) => this.setState({ result: res }));
};

這就是我使用 React 顯示結果的方式:

const { result } = this.state;

<div>{result}</div>

在此處輸入圖像描述

我不知道你為什么寫下面的代碼:

this.state.design = await this.state.contract.methods

The ReactJS doesn't have two-way-data-binding , The ReactJS is not like VueJS or Angular, for changing state you should use this.setState or useState . this.state.design =從不改變任何狀態。

現在回答你的問題。 為結果設置初始 state,如下所示:

this.state = {
  result: undefined,
};

然后在 JSX 中編寫如下:

const { result } = this.state;

<div>
  {result && result.map((item, index) => (
    <div key={item.uniqueThing}>{item.title}</div>
  ))}
</div>

實際上,您不需要index ,我只是想知道您可以擁有它。 即使你可以寫得更好:

const { result } = this.state;

<div>
  {result && result.map(({ title, uniqueThing }) => (
    <div key={uniqueThing}>{title}</div>
  ))}
</div>

注意:您絕對應該將key傳遞給 map 回調 function 返回的第一個 JSX 元素,並且它應該是唯一的,請不要使用index它對 Z217C80CED5A5D142B0E105A8641 有不好的代價,有時會陷入錯誤的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM