首页 > 解决方案 > 如何使用返回的 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,没有别的。

非常感谢!

标签: jsonreactjsaxiosweb3

解决方案


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Basic_assignment

解构运算符是你的朋友

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 });
});

推荐阅读