简体   繁体   English

在 React 组件中渲染返回的 Solidity 映射值

[英]Rendering returned Solidity mapping values in React component

Here is a Solidity contract:这是一个 Solidity 合约:

pragma solidity ^0.8.7;

contract SomeContract {

  address public manager;
  uint public theNumberNine;
  mapping (string => mapping (address => uint)) public stringToAddrToInt;

  constructor() {
    manager = msg.sender;
    theNumberNine = 9;
  }

  function setInt(string memory someString) public {
    stringToAddrToInt[someString][msg.sender] = theNumberNine;
  }

  function getIntFromMapping(string memory someString) public view returns (uint) {
    return stringToAddrToInt[someString][msg.sender];
  }
}

Here is a JSX frontend:这是一个 JSX 前端:

import React, { Component } from 'react';
import { Button } from 'semantic-ui-react';
import SomeContract from 'someContract';
import Web3 from 'web3';

class SomeClass extends Component {
  static async getInitialProps(props) {
    const { address, myString } = props.query;
    const contractInstance = SomeContract(address);
    const provider = new Web3.providers.HttpProvider(
      'https://kovan.infura.io/my-endpoint-here'
    );
    const web3 = new Web3(provider);
    const accounts = await web3.eth.getAccounts();
    await contractInstance.methods.setInt(myString).send({
      from: accounts[0]
    });
    const intFromSolidity = await contractInstance.methods.getIntFromMapping(myString).call();

    return { intFromSolidity };
  }

  onSubmit = async () => {
    console.log(this.props.intFromSolidity);
  }

  render() {
    return (
      <Button basic onClick={this.onSubmit}>
        I should output 9
      </Button>
    );
  }
}

Expected output: 9预期 output:9
Actual output: undefined实际 output:未定义

The console log is undefined, but when calling getIntFromMapping in Remix, it outputs 9 as expected.控制台日志未定义,但在 Remix 中调用 getIntFromMapping 时,它按预期输出 9。 I would appreciate a little enlightenment on the reason for this behavior, and how to properly return solidity mapping values for use in React components.对于这种行为的原因,以及如何正确返回用于 React 组件的 Solidity 映射值,我将不胜感激。

Depending on next.js version that you are using, you might need to return from initialProps like this根据您使用的 next.js 版本,您可能需要像这样从 initialProps 返回

return { props:{intFromSolidity} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM