我正在尝试使用Substrate UI来显示运行时模块中可用的功能。该代码是用React编写的。我正在尝试创建一个组件,以帮助我跟踪结构的所有先前状态。
runtime.template.assets(i)
调用以十六进制值i
作为输入,并返回具有关键字kitty
(具有十六进制值)的结构parent_hash
。我希望执行while
循环,直到达到一个特殊的十六进制值,在本例中为"0x11da6d1f761ddf9bdb4c9d6e5303ebd41f61858d0a5647a1a7bfe089bf921be9"
,我将其转换为String
以达到终止条件。
请忽略<KittyShrieks>
标记,因为它是我用来在UI中显示某些值的东西。基本上,我无法在while循环中完成此操作
var kitty = await runtime.template.kitties(i);
.
.
i = kitty.parent_hash;
所需的代码
export class TrackCards extends ReactiveComponent {
constructor(props) {
super(['hash'])
}
unreadyRender() {
return <span>Nothing to track</span>
}
async readyRender() {
let kitties = [];
var i = this.state.hash;
var root_hash = "0x11da6d1f761ddf9bdb4c9d6e5303ebd41f61858d0a5647a1a7bfe089bf921be9";
var root = "17,218,109,31,118,29,223,155,219,76,157,110,83,3,235,212,31,97,133,141,10,86,71,161,167,191,224,137,191,146,27,233";
var iter = 0;
var a;
while ((root != i.toString()) {
var kitty = await runtime.template.kitties(i);
kitties.push(
<div className="column" key={i}>
<KittyShrieks
owner_count = {runtime.template.kittyHistoryCount(i)}
hash_original = {this.state.hash}
/>
</div>
);
i = kitty.parent_hash;
}
return <div className="ui stackable six column grid">{kitties}</div>;
}
}
我认为使用异步渲染不是有效的方法,但是我这样做是因为我似乎别无选择,只能使用await keyword
。因此,问题在于UI无法加载,并且出现以下错误:
Uncaught Invariant Violation: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
如果我删除async
关键字var kitty = await runtime.template.kitties(i);
语句并在循环末尾插入break
语句,则UI加载良好。因此,不允许我遍历循环。
我对React甚至Java都是新手。任何帮助将不胜感激。
答案 0 :(得分:0)
组件始终需要能够渲染某些内容(或null
)。在这里,实际上是在要求React渲染promise
,因此是您的错误。
您应该将此逻辑提取到componentDidMount()
生命周期中。以您的代码为例,它看起来可能像这样:
export class TrackCards extends ReactiveComponent {
constructor(props) {
super(['hash'])
this.state = {
kitties: []
}
}
async componentDidMount() {
const kitties = [];
var i = this.state.hash;
var root_hash = "0x11da6d1f761ddf9bdb4c9d6e5303ebd41f61858d0a5647a1a7bfe089bf921be9";
var root = "17,218,109,31,118,29,223,155,219,76,157,110,83,3,235,212,31,97,133,141,10,86,71,161,167,191,224,137,191,146,27,233";
var iter = 0;
var a;
while (root != i.toString()) {
var kitty = await runtime.template.kitties(i);
kitties.push(
<div className="column" key={i}>
<KittyShrieks
owner_count = {runtime.template.kittyHistoryCount(i)}
hash_original = {this.state.hash}
/>
</div>
);
i = kitty.parent_hash;
}
this.setState(
kitties
);
}
render () {
const { kitties } = this.state;
return (
kitties.length
? <div className="ui stackable six column grid">{kitties}</div>
: <span>Nothing to track</span>
)
}
}
我们最初返回<span>Nothing to track</span>
,而您正在等待kitties
完成。