![](/img/trans.png)
[英]How to remove specific item from JSON object correctly in REACT js?
[英]How to set state of a react component with a specific item from a returned json object?
這是上一個線程的后續問題
我的react組件將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})
我返回了看似無窮無盡的構造console.log({ items: this.state.items})
和道具數組。
我努力了
this.setState({ items : items.transactionHash });
和console.log( { items: this.state.items.transactionHash})
。
我需要做的是set.state
,上面的json僅包含transactionHash
,僅此而已。
非常感謝!
破壞者是你的朋友
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 });
});
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({
items: {
transactionHash
}
});
});
您需要找出transactionHash在json對象中的位置。
要查找結構,請首先記錄輸出並檢查控制台。
console.log(res.data)
如果讓我們假設它在數據對象下,例如:
"data: {
"transactionHash": "0x12c65523743ed169c764553ed2e0fb2af1710bb20a41b390276ffc2d5923c6a9"
}
這是設置狀態的方式:
axios.post(
"http://compute.amazonaws.com:3000/users",
{
value: this.props.value,
fileName: this.props.fileName,
hash: this.props.hash
}
)
.then(res => {
console.log(res.data)
this.setState({ hash: res.data.transactionHash });
});
最終狀態將是:
{
items: {},
hash: "0x12c65523743ed169c764553ed2e0fb2af1710bb20a41b390276ffc2d5923c6a9"
}
您當然可以使用解構,但是首先我們需要知道從服務器返回的數據的形狀
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.