如何将json数据返回到react状态?

IT技术 json reactjs express web3
2021-04-17 22:32:34

我有一个react组件,它可以连接.post到一个快速服务器(我自己的服务器)。服务器用于web3在 上签署交易Ethereum一旦交易被包含在一个区块中,一个json对象就会返回给服务器。它看起来像这样:

{ blockHash: '0xcd08039bac40e2865886e8f707ce9b901978c339d3abb81516787b0357f53fbd',
  blockNumber: 4611028,
 ...other data...
  transactionHash: '0x12c65523743ed169c764553ed2e0fb2af1710bb20a41b390276ffc2d5923c6a9',
  transactionIndex: 1 }

我需要将 存储transactionHash到上述组件的状态中。我已经搜索了 2 天,可能遗漏了一些非常明显的东西。

这是服务器端代码还是客户端代码?我是否需要学习和使用 async 因为与 交谈的固有时间延迟Ethereum

任何帮助表示赞赏!

谢谢

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);
      })
  }
然后您可以使用 JS 点符号来访问该值。setState({ 交易:items.transactionHash });
2021-05-23 22:32:34
我已经更新了示例以包含 axios 库。
2021-06-06 22:32:34
谢谢你的带领。我目前正在使用 axios,所以也许我需要修改。给我一两天时间接受。我很感激 :)
2021-06-08 22:32:34
谢谢,那确实存储items在状态中。我只想存储transactionHash,仅此而已。你认为我应该开一个单独的问题吗?
2021-06-08 22:32:34
不幸的是,这行不通。我打开了一个新线程,这让我陷入了困境…… stackoverflow.com/questions/53749081/ ……
2021-06-19 22:32:34