json - 如何使用返回的 json 对象中的特定项目设置反应组件的状态?
问题描述
这是上一个帖子的后续问题
我的反应组件使axios.post
一个express
服务器。服务器用于web3
将交易签署到Ethereum
. Ethereum
返回以下json
对象。值得注意的是,json
返回需要一些时间(几秒到几分钟,具体取决于矿工):
{ blockHash: '0xcd08039bac40e2865886e8f707ce9b901978c339d3abb81516787b0357f53fbd',
blockNumber: 4611028,
...other data...
transactionHash: '0x12c65523743ed169c764553ed2e0fb2af1710bb20a41b390276ffc2d5923c6a9',
transactionIndex: 1 }
这是我用来制作axios.post
和设置状态的代码:
import React from "react";
import PaypalExpressBtn from "react-paypal-express-checkout";
import axios from "axios";
export default class Pay extends React.Component {
constructor(props) {
super(props);
this.state = {
items: {}
};
}
render() {
const onSuccess = payment => {
axios
.post("http://compute.amazonaws.com:3000/", {
value: this.props.value,
fileName: this.props.fileName,
hash: this.props.hash
})
.then(response => console.log(response.data))
.catch(function(error) {
console.log(error);
});
console.log(payment);
};
let env = "sandbox"; // you can set here to 'production' for production
let currency = "USD"; // or you can set this value from your props or state
let total = 3.33; // same as above, this is the total amount (based on
const client = {
sandbox:
"...key...",
production: "YOUR-PRODUCTION-APP-ID"
};
return (
<div>
<PaypalExpressBtn
onSuccess={onSuccess}
/>
</div>
);
}
}
当我console.log({ items: this.state.items})
返回时,一堆看似无穷无尽的构造器和道具。
我努力了
this.setState({ items : items.transactionHash });
并且console.log(
{ items: this.state.items.transactionHash})
,两者都不起作用。
我需要做的set.state
只是transactionHash
来自上面的 json,没有别的。
非常感谢!
解决方案
解构运算符是你的朋友
axios.post(
"http://compute.amazonaws.com:3000/users",
{
value: this.props.value,
fileName: this.props.fileName,
hash: this.props.hash
}
)
.then(res => {
const items = res.data;
const {transactionHash} =items
this.setState({ transactionHash });
});
推荐阅读
- javascript - React-bootstrap - 无效的挂钩调用 - ButtonDropdown
- java - JDBC:在 UTC 中插入时间戳
- marklogic - MarkLogic 不强制执行函数签名
- python - 当我使用函数删除某些子字符串时,此检查会在分配前警告局部变量
- java - 为什么在初始化父级部分时子类构造函数使用重写版本的方法?
- r - 我可以使用 gsub 函数找到一个模式并用 2 个不同的模式替换它吗?
- r - R - 如何在没有 for 循环的情况下拆分汇总表?
- neural-network - 输入 flatten 值来自全连接 1 (fc1) 层(MNIST 示例)
- python - 使用 Python3 实时绘制多个图
- javascript - 有没有一种方法可以让我在返回结果之前等待 javascript 函数完成