小编典典

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

reactjs

我有一个对.post快速服务器(我自己的服务器)进行反应的组件。服务器用于web3在上签署交易Ethereum。一旦将交易包含在一个块中,就将一个json对象返回给服务器。看起来像这样:

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

我需要将存入transactionHash上述组件的状态。我已经搜索了2天,可能丢失了一些非常明显的内容。

这是服务器端代码还是客户端代码?由于与之交谈的固有时间延迟,我是否需要学习和使用异步Ethereum

任何帮助表示赞赏!

谢谢


阅读 285

收藏
2020-07-22

共1个答案

小编典典

要发出发布请求,您必须通过componentDidMount在客户端执行此请求,然后像往常一样存储响应。您可以在此处找到完整的示例:react页面上的https://reactjs.org/docs/faq-
ajax.html。

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);
      })
  }
2020-07-22