简体   繁体   English

为什么我的交易没有呈现? --反应 & Java

[英]Why aren't my transactions rendering? --React & Java

I can't seem to figure out where I'm going wrong in my code to cause my app to not completely render the transactions.我似乎无法弄清楚我的代码哪里出了问题,导致我的应用程序无法完全呈现交易。 I double-checked my variables in both mySQL & in React, so it's not a variable issue.我在 mySQL 和 React 中仔细检查了我的变量,所以这不是变量问题。 I'm not sure if the error lies on the front-end (React) side, but I'm fairly sure that it does.我不确定错误是否存在于前端(React)端,但我相当确定它确实存在。

Here is my code for TransactionsList:这是我的 TransactionsList 代码:

function TransactionsList() {

 const [transactions, setTransactions] = useState([]);
 
 useEffect(() => {
   let username = AuthenticationService.getLoggedInUserName();
   TransactionDataService.retrieveAllTransactions(
     username
   ).then((transactions) => setTransactions([transactions]));
  }, []);
   
  return (
    <CardColumns style={{ padding: "20px" }}>
      {transactions.map((transaction) => (
        <TransactionCard transaction={transaction} />
      ))}
    </CardColumns>
  );
}

Here is my code for TransactionCard:这是我的 TransactionCard 代码:

const username = AuthenticationService.getLoggedInUserName();

  TransactionDataService.retrieveTransaction(username, useState.id).then(
    (response) =>
      useState({
        accountName: response.data.accountName,
        transactionDate: response.data.transactionDate,
        transactionType: response.data.transactionType,
        depositCategory: response.data.depositCategory,
        withdrawalCategory: response.data.withdrawalCategory,
        transactionAmount: response.data.transactionAmount,
        notes: response.data.notes,
      })
  );
    

export default function TransactionCard(props) {
  const classes = useStyles();

  const [expanded, setExpanded] = useState(false);

  const handleExpandClick = () => {
    setExpanded(!expanded);
  };
 
 const { transaction } = props; 

//  const { data: transactions } = useSWR((url) =>
//    fetch(url).then((_) => _.json())
//  );
 
  const getTransactions = (url) => fetch(url).then((_) => _.json());

  const { data: transactions } = useSWR(
    `http://localhost:8080/jpa/users/${username}/transactions`,
    getTransactions
  );

  useEffect(() => {
    console.log(transactions);
  }, [transactions]);
 
  function handleEdit(id) {
    console.log("handle edit");
    alert("you clicked edit");
  }

  function handleDelete(id) {
    console.log("handle delete");
  }

  return (
    <>
      <Card className={classes.card}>
        <center>
          <CardHeader tag="h3">{transaction.accountName}</CardHeader>
          <CardText>{transaction.transactionType}</CardText>
          <CardText>
            {moment.utc(transaction.transactionDate).format("MMM-DD-YYYY")}
          </CardText>
          <CardText>{transaction.depositCategory}</CardText>
          <CardText>{transaction.withdrawalCategory}</CardText>
          <CardText>{"$" + parseFloat(transaction.transactionAmount)}</CardText>
        </center>

Here is the relevant Java code:下面是相关的Java代码:

@GetMapping("/jpa/users/{username}/transactions")
    public List<Transaction> getAllTransactions(@PathVariable String username) {
        return transactionJpaRepository.findByUsername(username);
    }

Here are my findings from when I did a curl:以下是我做 curl 时的发现:

StatusCode        : 200        
StatusDescription :
Content           : [{"id":200
                    1,"usernam 
                    e":"Tim"," 
                    accountNam 
                    e":"BOA"," 
                    transactio 
                    nDate":"20 
                    21-03-13T0 
                    2:19:33.00 
                    0+00:00"," 
                    transactio 
                    nType":"de 
                    posit","de 
                    positCateg 
                    ory":"payr 
                    oll","with 
                    drawalCate 
                    gory":null 
                    ,"transact 
                    ionAmount" 
                    ...        
RawContent        : HTTP/1.1   
                    200        
                    Vary: Orig
                    in,Access- 
                    Control-Re 
                    quest-Meth 
                    od,Access- 
                    Control-Re 
                    quest-Head 
                    ers        
                    Transfer-E 
                    ncoding: 
                    chunked    
                    Keep-Alive 
                    :
                    timeout=60 
                    Connection 
                    :
                    keep-alive 
                    Content-Ty 
                    pe: applic 
                    ation/json 
                    Da...
Forms             : {}
Headers           : {[Vary, Or
                    igin,Acces 
                    s-Control- 
                    Request-Me 
                    thod,Acces 
                    s-Control- 
                    Request-He 
                    aders], [T
                    ransfer-En
                    coding,    
                    chunked],  
                    [Keep-Aliv 
                    e, timeout 
                    =60], [Con 
                    nection, k 
                    eep-alive] 
                    ...}       
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : mshtml.HTM
                    LDocumentC
                    lass
RawContentLength  : 1387

Here is my POJO:这是我的 POJO:

@Entity
public class Transaction {
    
    @Id
    @GeneratedValue
    private long id;
    private String username;
    private String accountName;
    private Date transactionDate;
    private String transactionType;
    private String depositCategory;
    private String withdrawalCategory;
    private double transactionAmount;
    private String notes;

    protected Transaction() {
        
    }

    public Transaction(long id, String username, String accountName, Date transactionDate, String transactionType,
            String depositCategory, String withdrawalCategory, double transactionAmount, String notes) {
        super();
        this.id = id;
        this.username = username;
        this.accountName = accountName;
        this.transactionDate = transactionDate;
        this.transactionType = transactionType;
        this.depositCategory = depositCategory;
        this.withdrawalCategory = withdrawalCategory;
        this.transactionAmount = transactionAmount;
        this.notes = notes;
    }


    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAccountName() {
        return accountName;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    public Date getTransactionDate() {
        return transactionDate;
    }

    public void setTransactionDate(Date transactionDate) {
        this.transactionDate = transactionDate;
    }

    public String getTransactionType() {
        return transactionType;
    }

    public void setTransactionType(String transactionType) {
        this.transactionType = transactionType;
    }

    public String getDepositCategory() {
        return depositCategory;
    }

    public void setDepositCategory(String depositCategory) {
        this.depositCategory = depositCategory;
    }

    public String getWithdrawalCategory() {
        return withdrawalCategory;
    }

    public void setWithdrawalCategory(String withdrawalCategory) {
        this.withdrawalCategory = withdrawalCategory;
    }

    public double getTransactionAmount() {
        return transactionAmount;
    }

    public void setTransactionAmount(double transactionAmount) {
        this.transactionAmount = transactionAmount;
    }

    public String getNotes() {
        return notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + (int) (id ^ (id >>> 32));
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Transaction other = (Transaction) obj;
        if (id != other.id)
            return false;
        return true;
    }
}

Debugging reveals this once I stepped over transactionJpaRepository.findByUsername(username) : "Hibernate: select transactio0_.id as id1_1_, transactio0_.account_name as account_2_1_, transactio0_.deposit_category as deposit_3_1_, transactio0_.notes as notes4_1_, transactio0_.transaction_amount as transact5_1_, transactio0_.transaction_date as transact6_1_, transactio0_.transaction_type as transact7_1_, transactio0_.username as username8_1_, transactio0_.withdrawal_category as withdraw9_1_ from transaction transactio0_ where transactio0_.username=?" Debugging reveals this once I stepped over transactionJpaRepository.findByUsername(username) : "Hibernate: select transactio0_.id as id1_1_, transactio0_.account_name as account_2_1_, transactio0_.deposit_category as deposit_3_1_, transactio0_.notes as notes4_1_, transactio0_.transaction_amount as transact5_1_, transactio0_.交易日期为transact6_1_,transactio0_.transaction_type为transact7_1_,transactio0_.username为username8_1_,transactio0_.withdrawal_category为来自交易transactio0_的withdraw9_1_,其中transactio0_.username=?”

It's a lot of code to follow, but one thing stands out at me when I glance over this code...有很多代码要遵循,但是当我浏览这段代码时,有一件事让我印象深刻......

You set your state-managed transactions up to be an array of transaction as such:您将状态管理的交易设置为一个交易数组,如下所示:

const [transactions, setTransactions] = useState([]);

Then you clearly have a local object coming back from your TDS promise called "transactions" which I'm guessing would ALSO be an array.然后,您显然有一个本地 object 从您的 TDS promise返回,称为“事务”,我猜它也将是一个数组。

TransactionDataService.retrieveAllTransactions(username)
.then((transactions) => setTransactions([transactions]));

So if that's all true, then your state-driven setTransactions call here is taking your Promise-Returned array and wrapping it into a single-array element...因此,如果这一切都是真的,那么您在此处的状态驱动 setTransactions 调用将采用您的 Promise-Returned 数组并将其包装到单个数组元素中......

So your state-driven transactions after this would look like:因此,在此之后您的状态驱动事务将如下所示:

transactions = [
   [ tx1, tx2, tx3, .... ]
]

In this case, it makes sense that your state-driven transactions object only has one record in it.在这种情况下,您的状态驱动事务 object 中只有一条记录是有意义的。 Although that one-record should be the array of all transactions..虽然那条记录应该是所有交易的数组..

If this is the case, the solution is to fix your setTransactions to NOT have a [] wrapping your promise-returned transactions array.如果是这种情况,解决方案是将您的 setTransactions 修复为没有 [] 包装您的承诺返回的交易数组。

That said, reading the comments it does sound like curl/back-end needs addressing before you hit this.也就是说,阅读评论听起来确实像 curl/back-end 需要解决,然后再点击它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM