我有一个react组件,它使Express服务器(我自己的服务器)成为.post
。服务器使用web3
在Ethereum
上签署交易。交易包含在块中后,json
对象将返回到服务器。看起来像这样:
{ blockHash: '0xcd08039bac40e2865886e8f707ce9b901978c339d3abb81516787b0357f53fbd',
blockNumber: 4611028,
...other data...
transactionHash: '0x12c65523743ed169c764553ed2e0fb2af1710bb20a41b390276ffc2d5923c6a9',
transactionIndex: 1 }
我需要将transactionHash
存储到上述组件的状态中。我已经搜索了2天,可能丢失了一些非常明显的内容。
这是服务器端代码还是客户端代码?
由于与Ethereum
通话时固有的时间延迟,我是否需要学习和使用异步功能?
感谢您的帮助!
谢谢
答案 0 :(得分:1)
要发出发布请求,您必须通过componentDidMount在客户端执行此请求,然后像平常一样存储响应。您可以在此处找到完整的示例:https://reactjs.org/docs/faq-ajax.html在react页面上。
fetch("https://api.example.com/items")
.then(res => res.json())
.then(response => this.setState(response));
您必须将提取操作调整为后期请求,但是您可以在此处找到与提取有关的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch("https://api.example.com/items", {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(response => this.setState(response))
.catch(error => console.error('Error:', error));
编辑(例如Axios):
componentDidMount() {
axios.get("https://api.example.com/items")
.then(res => {
const items = res.data;
this.setState(items);
})
}