You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js处理POST数据及XRPL NFT前端渲染与数据映射问题

解决Next.js中XRPL NFT数据渲染与组件传递问题

问题概述

在Next.js项目中调用XRPL接口获取NFT数据,后端已返回包含account_nfts数组的JSON(含URI、NFTokenID等字段),但前端无法渲染这些数据,也不清楚如何将数据传递给后续组件。

解决方案步骤

1. 用React状态管理存储NFT数据

在组件中添加useState保存获取到的NFT列表,让数据能在组件内被访问和渲染:

import React, { useState } from "react";
import styles from "../styles/Home.module.css";

const Sellnft = () => {
  // 新增状态存储NFT列表
  const [nftList, setNftList] = useState([]);

  const handleSubmit = async (e) => {
    e.preventDefault();

    const data = {
      walletAddress: e.target.walletAddress.value,
    };
    const JSONdata = JSON.stringify(data);

    const endpoint = "/api/getnft";
    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSONdata,
    };
    const response = await fetch(endpoint, options);
    const result = await response.json();
    
    // 将获取到的NFT数组存入状态
    if (result.result?.account_nfts) {
      setNftList(result.result.account_nfts);
    }
  };

  // 后续渲染逻辑
};

export default Sellnft;

2. 渲染NFT数据到页面

在JSX中添加渲染逻辑,遍历nftList展示NFT信息,注意XRPL返回的URI是Base64编码,需要解码:

return (
  <div>
    <main className={styles.main}>
      <h1 className={styles.title}>Sell your NFT</h1>

      <p className={styles.description}>Look for the Nft you want to sell</p>
      <div className={styles.containerWhite}>
        <form onSubmit={handleSubmit}>
          <label htmlFor="walletAddress">Account Address:</label>
          <input type="text" name="walletAddress" id="walletAddress" />
          <br />
          <button type="submit">Search NFT</button>
        </form>

        {/* 新增:渲染NFT列表 */}
        {nftList.length > 0 && (
          <div className={styles.nftList}>
            <h2>Your NFTs</h2>
            {nftList.map((nft, index) => {
              // 解码Base64格式的URI
              const decodedUri = nft.URI ? atob(nft.URI) : "No URI";
              return (
                <div key={index} className={styles.nftCard}>
                  <p><strong>Token ID:</strong> {nft.NFTokenID}</p>
                  <p><strong>URI:</strong> {decodedUri}</p>
                  {/* 触发跳转/传递数据的按钮 */}
                  <button onClick={() => handleSelectNft(nft)}>Sell This NFT</button>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </main>
  </div>
);

3. 传递NFT数据给下一个组件

如果需要将选中的NFT传递给其他组件,推荐两种实用方式:

方式一:通过Next.js路由传递

使用next/navigation的useRouter传递JSON格式的NFT数据:

import { useRouter } from 'next/navigation';

const Sellnft = () => {
  const router = useRouter();

  const handleSelectNft = (nft) => {
    // 将NFT数据编码后通过路由参数传递
    router.push(`/sell-confirm?nft=${encodeURIComponent(JSON.stringify(nft))}`);
  };

  // 其他逻辑...
};

在目标组件/sell-confirm中接收数据:

import { useSearchParams } from 'next/navigation';

const SellConfirm = () => {
  const searchParams = useSearchParams();
  const nftData = searchParams.get('nft');
  const nft = nftData ? JSON.parse(decodeURIComponent(nftData)) : null;

  return (
    <div>
      <h1>Confirm Sell</h1>
      {nft && (
        <div>
          <p>Token ID: {nft.NFTokenID}</p>
          <p>URI: {atob(nft.URI)}</p>
        </div>
      )}
    </div>
  );
};

export default SellConfirm;

方式二:通过组件props传递

如果目标组件是当前组件的子组件,直接通过props传递:

// 导入子组件
import NftSellForm from './NftSellForm';

const Sellnft = () => {
  const [selectedNft, setSelectedNft] = useState(null);

  const handleSelectNft = (nft) => {
    setSelectedNft(nft);
  };

  return (
    // ... 其他渲染代码
    {selectedNft && <NftSellForm nft={selectedNft} />}
  );
};

4. 后端代码优化建议

当前后端函数名与功能不符,且缺少错误处理,建议修改:

const xrpl = require("xrpl");

export default async function getNft(req, res) {
  // 限制请求方法为POST
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const net = "wss://xls20-sandbox.rippletest.net:51233";
  try {
    const standby_wallet = xrpl.Wallet.fromSecret(req.body.walletAddress);
    const client = new xrpl.Client(net);
    await client.connect();

    const nfts = await client.request({
      method: "account_nfts",
      account: standby_wallet.classicAddress,
    });

    res.status(200).json(nfts);
    client.disconnect();
  } catch (error) {
    // 返回错误信息
    res.status(400).json({ error: 'Invalid wallet secret or network error' });
  }
}

内容的提问来源于stack exchange,提问作者Saad Siddiqui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 19:21:34