如何将json数据返回到React状态? [英] How to return json data to a react state?

查看:168
本文介绍了如何将json数据返回到React状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个react组件,它对快递服务器(我自己的服务器)起一个.post的作用.服务器使用web3Ethereum上签署交易.一旦将事务包含在一个块中,就会将json对象返回给服务器.看起来像这样:

I have a react component that makes a .post to an express server (my own server). The server uses web3 to sign a transaction on Ethereum. Once the transaction is included in a block, a json object is returned to the server. It looks like this:

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

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

I need to store the transactionHash into the state of the above component. I have been searching for 2 days and am probably missing something very obvious.

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

Is this server-side or client-side code? Do I need to learn and use async because of the inherent time delay in talking to Ethereum?

感谢您的帮助!

谢谢

推荐答案

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

To make the post request, you would have to perform this one the client via the componentDidMount, and then store the response as you would normally. You can find full examples here: https://reactjs.org/docs/faq-ajax.html on the react page.

fetch("https://api.example.com/items")
    .then(res => res.json())
    .then(response => this.setState(response));

您必须将获取操作调整为后期请求,但是您可以在此处找到与获取有关的更多信息:

You would have to adjust the fetch operation to be a post request but you can find more information related to fetching here: 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):

Edit (example with Axios):

componentDidMount() {
    axios.get("https://api.example.com/items")
      .then(res => {
        const items = res.data;
        this.setState(items);
      })
  }

这篇关于如何将json数据返回到React状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆