React + Axios调用Rarible API时出现TypeError: nfts.map is not a function问题求助
Let's break down why you're seeing this error and walk through the fixes step by step:
The Root Causes
You're passing a Promise, not an array, to
NFTContainer
YourfetchOwnedTokensis an async function, which means calling it directly (const data = fetchOwnedTokens(address)) returns a Promise object, not the actual NFT array. Promises don't have amapmethod, hence the TypeError.Unnecessary array wrapping in
fetchOwnedTokens
You're returning[result.data.items]which wraps the API's already array-shapeditemsresponse in another array. This would create a 2D array even if you resolved the Promise, which would also cause issues withmap.
Step 1: Fix the Data Fetching Function
First, update fetchOwnedTokens to return the raw items array (or an empty array as a fallback) instead of wrapping it:
const fetchOwnedTokens = async (owner) => { try { const result = await axios.get(`https://ethereum-api.rarible.org/v0.1/nft/items/byOwner?owner=${owner}`) // Return the items array directly, or empty array if it's undefined return result.data.items || [] } catch (err) { console.error(err) return [] } }
Step 2: Handle Async Data in Your Component
React components can't be async functions directly, so we'll use useState to store the NFT data and useEffect to trigger the async fetch when the wallet address loads:
export const ChooseProductView = () => { const { address } = useWeb3Context() const [nfts, setNfts] = useState([]) const [isLoading, setIsLoading] = useState(true) useEffect(() => { // Exit early if there's no address if (!address) return const loadOwnedNFTs = async () => { setIsLoading(true) // Await the Promise to get the actual array const ownedTokens = await fetchOwnedTokens(address) setNfts(ownedTokens) setIsLoading(false) } loadOwnedNFTs() }, [address]) // Re-run when the address changes if (!address) { return renderNotConnectedContainer() } // Add a loading state for better UX if (isLoading) { return <div className="flex items-center justify-center">Loading your NFTs...</div> } return ( <div className="flex items-center justify-center"> <NFTContainer nfts={nfts} /> </div> ) }
Step 3: Verify NFTContainer Works with Valid Arrays
Your existing NFTContainer code is fine as long as nfts is an array. The fixes above ensure that nfts will always be an array (either empty or filled with NFT data), so map will work correctly.
With these changes, you'll resolve the TypeError, properly load your NFT data asynchronously, and add a better user experience with a loading state.
内容的提问来源于stack exchange,提问作者rohit

