简体   繁体   English

挂载React.js时如何获取api

[英]How to fetch api when mounting of React.js

I am trying to display Nfts on my page but it gives and error like Uncaught TypeError: Cannot read properties of undefined (reading 'map').我试图在我的页面上显示 Nfts,但它给出了类似 Uncaught TypeError: Cannot read properties of undefined (reading 'map') 的错误。 So my nfts variable is an array but still mapping is not possible.所以我的 nfts 变量是一个数组,但仍然无法映射。 Here is my component:这是我的组件:

import React, { useState, useEffect } from "react";
import { Container, Row, Col } from 'react-bootstrap';
import axios from 'axios';
import { Link } from "react-router-dom";

const Nfts = ({ walletAddress }) => {
    const sender = "abc";
    const apikey = "def";
    const [nfts, setNfts] = useState();
    const getNftData = () => {
        axios.get(``)
            .then(output => {
                setNfts(output.data.result)
        })
    }
    useEffect(() => {
        getNftData();
    }, []);
    return (
        <section className="my-nfts">
            <Container>
                <Row>
                    {nfts == '' ?
                        <><div className='mynft-title'>My NFTs</div>
                            <div className="empty-nft">There is no NFT to display</div></> : (
                            <>
                                {nfts.map((nft, index) => {
                                    if (nft.from == sender && nft.to == walletAddress) {
                                        <Col xs={12} md={12} lg={4}>
                                            <div key={index}>{nft}</div>
                                        </Col>

                                    }
                                })}
                            </>
                        )}
                </Row>
            </Container>
        </section>
    );
}

export default Nfts;

So I beleive it doesnt render at the first time when page is loaded.所以我相信它不会在页面加载时第一次呈现。 But i might be wrong.但我可能是错的。 What do you think I am making wrong?你认为我做错了什么? Thanks..谢谢..

Just give the nfts State an empty array as initial value For example只需给 nfts State 一个空数组作为初始值例如

const [nfts, setNfts] = useState([]);

or或者

In the HTML use a conditional statement to not use map method if the nfts still undefined For example在 HTML 如果 nfts 仍未定义,则使用条件语句不使用 map 方法例如

nfts && nfts.map(() => { ... } )

Also, I noticed that the API URL is empty.另外,我注意到 API URL 是空的。 ( I'm not sure if you mean that because you don't want to show the API URL in the question or you missing that ). (我不确定你的意思是不是因为你不想在问题中显示 API URL 或者你错过了那个)。

I'm suggest much cleaner syntax for you我建议你使用更简洁的语法

 nfts?.map((item) => {...item } )

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

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