You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

读取Solidity工厂合约数组时React调用map报undefined错如何解决

问题原因

  • getInitialProps 是Next.js框架专属的页面组件属性注入API,普通React项目不支持该方法,它不会被自动执行,你返回的migration/migrations字段不会挂载到this.props上,导致this.props.migration/this.props.migrations为undefined,调用map方法自然抛出错误。
  • 第二个修改版本存在额外错误:renderMigrations是组件自身定义的方法,不是父组件传递的属性,不应该从this.props中读取,且调用方法需要加括号执行。
  • 未做兜底判断,即使后续数据请求逻辑修复,在异步请求完成前,数组为空/未初始化的状态下直接调用map也会触发报错。
  • 额外排查点:可先在控制台打印await factory.methods.getMigrations().call()的返回结果,确认合约实例、ABI、链连接配置正确,确实能拿到数组格式的返回值。

修复方案

如果是普通React项目,直接使用React标准的生命周期请求数据并存入state即可,修复后的完整代码如下:

import React from "react";
import web3 from "./web3";
import factory from "./factory";
import AccordionExampleStyled from "./components/Acordeon";
import { Card, Button } from "semantic-ui-react";
import 'semantic-ui-css/semantic.min.css'

class App extends React.Component {
  // 初始化state,给migrations默认空数组做兜底
  state = {
    migrations: []
  }

  // 组件挂载后执行异步请求拉取链上数据
  async componentDidMount() {
    const migrations = await factory.methods.getMigrations().call();
    // 将数据存入state触发重新渲染
    this.setState({ migrations });
  }

  renderCampaigns() {
    // 从state读取数组,默认空数组不会出现undefined问题
    const items = this.state.migrations.map((address) => {
      return {
        header: address,
        description: (
          <Button>See migration</Button>
        ),
        fluid: true,
      };
    });
    return <Card.Group items={items} />;
  }

  render() {
    return (
      <div>
        <center>
          <h2>MigrationHelper by DRIVENecosystem</h2>
          <p>
            <p><AccordionExampleStyled /></p>
            <p>List of all migrations </p>
            <p></p>
            {this.renderCampaigns()}
          </p>
        </center>
      </div>
    );
  }
};

export default App;

如果你确实使用的是支持getInitialProps的旧版Next.js,需要确认当前App组件是存放在pages目录下的页面级组件,只有这类组件才会自动执行getInitialProps注入属性,非页面组件不会触发该方法。

内容的提问来源于stack exchange,提问作者user15809778

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 13:15:02