开发者问题收集

如何向类组件发送 props

2022-07-09
132

我尝试将 props 发送到我的类组件。因此在父组件中:

<Child contract={_contract}/>

我像这样发送了 props。

在子组件中的一个函数中,我像这样调用 prop:

class Mint extends React.Component {
  constructor() {
    super();
    this.state = {
      balance: [],
    };
  }

  async componentDidMount() {
    await axios.get(`https://api.cronoscan.com/api?module=stats&action=tokensupply&contractaddress=${ADDRESS}&apikey=${apikey}`)
      .then(output => {
        this.setState({
          balance: output.data.result
        })
      })
  }

  mintNft = async () => { 
    var _mintAmount = Number(document.querySelector("[name=amount]").value); 
    var mintRate = Number(await this.props.contract.methods.cost().call()); 
    var totalAmount = mintRate * _mintAmount; 
    this.props.contract.methods.mint(
      localStorage
        .getItem('walletAddress'), _mintAmount)
        .send({
           from: JSON.parse(localStorage.getItem('walletAddress')),
           value: String(totalAmount)
        });
  }

  render() {
    const { balance } = this.state;
    const { nftdata } = this.state;
    return (
                      <button onClick={mintNft}>Mint</button>
    );
  }
}

export default Mint;

但它给出了错误 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'props')

等待您的答复。谢谢。

2个回答

请将其更改为

async function func() { 
  var mintRate = Number(await this.props.contract.methods.cost().call()); 
};

const func = async () => { 
  var mintRate = Number(await this.props.contract.methods.cost().call()); 
};

要理解此更改,您需要了解箭头函数与常规函数之间的区别。请查看 https://betterprogramming.pub/difference-between-regular-functions-and-arrow-functions-f65639aba256

Codesandbox 示例: https://codesandbox.io/s/laughing-snow-234or7

Nisharg Shah
2022-07-09

如果 mintNft 要在 Mint 组件内调用 访问 Mint 的 props,则应在范围内声明。将 mintNft 回调移到组件的范围内,以便它可以访问 Mint 组件的 this 并拥有已定义的 this.props 对象。

class Mint extends React.Component {
  constructor() {
    super();
    this.state = {
      balance: [],
    };
  }

  async componentDidMount() {
    await axios.get(`https://api.cronoscan.com/api?module=stats&action=tokensupply&contractaddress=${ADDRESS}&apikey=${apikey}`)
      .then(output => {
        this.setState({
          balance: output.data.result
        })
      })
  }

  mintNft = async () => { 
    var _mintAmount = Number(document.querySelector("[name=amount]").value); 
    var mintRate = Number(await this.props.contract.methods.cost().call()); 
    var totalAmount = mintRate * _mintAmount; 
    this.props.contract.methods.mint(
      localStorage
        .getItem('walletAddress'), _mintAmount)
        .send({
           from: JSON.parse(localStorage.getItem('walletAddress')),
           value: String(totalAmount)
        });
  }

  ...

  render() {
    const { balance, nftdata } = this.state;
    return (
      <button onClick={this.mintNft}> // <-- pass as callback
        Mint
      </button>
    );
  }
}
Drew Reese
2022-07-09