如何将returnjson数据转为react状态?
How to return json data to a react state?
我有一个 React 组件,可以 .post
连接到快速服务器(我自己的服务器)。服务器使用 web3
在 Ethereum
上签署交易。一旦交易被包含在一个块中,一个 json
对象就会返回给服务器。它看起来像这样:
{ blockHash: '0xcd08039bac40e2865886e8f707ce9b901978c339d3abb81516787b0357f53fbd',
blockNumber: 4611028,
...other data...
transactionHash: '0x12c65523743ed169c764553ed2e0fb2af1710bb20a41b390276ffc2d5923c6a9',
transactionIndex: 1 }
我需要将 transactionHash
存储到上述组件的状态中。我已经搜索了 2 天,可能遗漏了一些非常明显的东西。
这是服务器端代码还是客户端代码?
由于与 Ethereum
对话的固有时间延迟,我是否需要学习和使用异步?
感谢任何帮助!
谢谢
要发出 post 请求,您必须通过 componentDidMount 在客户端执行此请求,然后像往常一样存储响应。您可以在此处找到完整示例:https://reactjs.org/docs/faq-ajax.html 在反应页面上。
fetch("https://api.example.com/items")
.then(res => res.json())
.then(response => this.setState(response));
您必须将提取操作调整为 post 请求,但您可以在此处找到与提取相关的更多信息: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);
})
}
我有一个 React 组件,可以 .post
连接到快速服务器(我自己的服务器)。服务器使用 web3
在 Ethereum
上签署交易。一旦交易被包含在一个块中,一个 json
对象就会返回给服务器。它看起来像这样:
{ blockHash: '0xcd08039bac40e2865886e8f707ce9b901978c339d3abb81516787b0357f53fbd',
blockNumber: 4611028,
...other data...
transactionHash: '0x12c65523743ed169c764553ed2e0fb2af1710bb20a41b390276ffc2d5923c6a9',
transactionIndex: 1 }
我需要将 transactionHash
存储到上述组件的状态中。我已经搜索了 2 天,可能遗漏了一些非常明显的东西。
这是服务器端代码还是客户端代码?
由于与 Ethereum
对话的固有时间延迟,我是否需要学习和使用异步?
感谢任何帮助!
谢谢
要发出 post 请求,您必须通过 componentDidMount 在客户端执行此请求,然后像往常一样存储响应。您可以在此处找到完整示例:https://reactjs.org/docs/faq-ajax.html 在反应页面上。
fetch("https://api.example.com/items")
.then(res => res.json())
.then(response => this.setState(response));
您必须将提取操作调整为 post 请求,但您可以在此处找到与提取相关的更多信息: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);
})
}