【发布时间】:2026-01-31 13:20:02
【问题描述】:
我正在使用 React、Next.Js、semantic-ui-react 和 Solidity。我的目标是打印出用户地址(来自 MetaMask)和 ProjectTitle(由用户设置)作为语义 UI 反应卡的元信息。打印“标题”中的地址是有效的,但我无法将 ProjectTitle 打印为“元”。标题应该是一个字符串,但我收到了一个对象承诺。
static async getInitialProps() {
const projects = await factory.methods.getDeployedProjects().call();
return {
projects
};
}
async getProjectTitle(address) {
let title;
try {
title = await factory.methods.projectTitle(address).call();
} catch (err) {
console.log('err');
}
return title;
}
renderProjects() {
const items = this.props.projects.map(address => {
return {
header: address,
color: 'green',
description: (
<Link route={`/projects/${address}`}>
<a>View Project</a>
</Link>
),
**meta: this.getProjectTitle(address)**,
fluid: true,
style: { overflowWrap: 'break-word' }
};
}, );
return <Card.Group items={items} />
}
Solidity 合约的一部分:
address[] public deployedProjects;
mapping(address => string) public projectTitle;
function createProject(string startup, string title, string deadline, string description, uint wage) public {
address newProject = new Project(startup, title, deadline, description, wage, msg.sender);
projectTitle[newProject] = title;
deployedProjects.push(newProject);
}
function getDeployedProjects() public view returns (address[]) {
return (
deployedProjects
);
}
基本框架来自 Stephen Grider 的 Udemy 课程“以太坊和 Solidity:完整的开发者指南”。
【问题讨论】:
-
你不能“转换” Promise;您必须
await函数调用,否则显式使用.then()和回调函数。 -
好的,谢谢。这就是我所期待的答案。但这给我带来了另一个可能很简单的问题。我写了以下几行: var title = this.getProjectTitle(address).then(res => { console.log('res', res); }); 'res' 带来类型 (字符串),我需要。但我不知道如何将变量转移到元标记。也许我今天有点慢。
-
您可以将 projectTitle 异步调用移到 return { header: address, ... } 对象之前,然后等待 promise 返回。在 thennable 中,您可以使用 setState() 或任何在 thennable 范围之外记录结果的组件函数。不利的一面是,这使得 map() 与等待这些承诺的结果一一同步。更好的方法是使用新的 Promise.all() 并在初始渲染/挂载时获取项目名称,具体取决于它是函数还是 React.Component。
标签: javascript reactjs solidity semantic-ui-react next.js