【问题标题】:How to return json data to a react state?如何将 json 数据返回到反应状态?
【发布时间】:2019-05-13 05:40:05
【问题描述】:

我有一个反应组件,它可以将.post 发送到快速服务器(我自己的服务器)。服务器使用web3Ethereum 上签署交易。一旦交易被包含在一个块中,一个json 对象就会返回给服务器。它看起来像这样:

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

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

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

感谢任何帮助!

谢谢

【问题讨论】:

    标签: json reactjs express web3


    【解决方案1】:

    要发出 post 请求,您必须通过 componentDidMount 在客户端执行此请求,然后像往常一样存储响应。您可以在此处找到完整示例: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);
          })
      }
    

    【讨论】:

    • 感谢您的领导。我目前正在使用 axios,所以也许我需要修改。给我一两天时间接受。我很感激:)
    • 我已经更新了示例以包含 axios 库。
    • 谢谢,那确实在该州存储了items。我只想存储transactionHash,仅此而已。你认为我应该单独提出一个问题吗?
    • 然后您可以使用 JS 点符号来访问该值。 setState({ transaction: items.transactionHash });
    • 不幸的是,这不起作用。我打开了一个新线程,让我陷入了一个兔子洞......stackoverflow.com/questions/53749081/…
    猜你喜欢
    • 2019-12-24
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    相关资源
    最近更新 更多