簡體   English   中英

Uncaught (in promise) TypeError: profile.map is not a function in React.js

[英]Uncaught (in promise) TypeError: profile.map is not a function in React.js

每次嘗試使用 Axios 從第三方 API 源( https://randomuser.me/api/?results=50 )獲取數據時,都會出現上述錯誤。 問題似乎出在profile.map()函數上,因為當我 console.log 從 Axios 收到的響應時,它會顯示所有數據。 您會在返回開始處的list.jsx元素上找到profile.map()函數。 我已經看過以前的解決方案,並且很確定我已經完成了其中建議的幾乎所有內容。 這是代碼:

screen.jsx 顯示列表:

import "./screen.css";
import Header from "../header/header";
import List from "../list/list";

const Screen = () => {
    return (
        <div className="mainScreen">
            <Header></Header>
            <List></List>
        </div>
    );
}

export default Screen;

列表.jsx

import { useState, useEffect } from "react";
import axios from "axios";
import "./list.css";

const List = () => {
    const [profile, setData] = useState([]);

    useEffect(() => {
        axios.get("https://randomuser.me/api/?results=50").then(
            res => {
                console.log(res.data);
                setData(res.data);
                console.log(profile);
            }
        )
    });

    return (
        <div className="main">
            {/*This is where the error gets thrown*/}
            {profile.map((key, value) => <div className="listCard">
                <div className="userName">
                    <div style={{ margin: "10px 0 10px 20px" }}>Username : {profile[value].login.username}</div>
                </div>
                <div className="details">
                    <div className="topDetails">
                        <div className="nameAndEmail">
                            <div style={{ fontSize: "25px", fontWeight: "bold" }}>Mr Siddhartha Chatterjee</div>
                            <div style={{ fontSize: "20px", color: "rgb(128, 128, 112)", marginTop: "20px" }}>Email: siddc.8@gmail.com</div>
                        </div>
                        <div className="picture">
                            <div className="imageBox"></div>
                        </div>
                    </div>
                    <div className="bottomDetails">
                        <div className="nationality">
                            <div style={{ fontWeight: "bold", fontSize: "22px" }}>User for 6 years</div>
                            <div style={{ fontSize: "20px", marginBottom: "8px" }}>Age: 25</div>
                            <div style={{ fontSize: "20px", marginBottom: "8px" }}>Nationality: Indian</div>
                            <div style={{ fontSize: "18px", marginBottom: "8px" }}>#: 9073030038</div>
                        </div>
                        <div className="address">
                            <div style={{ textAlign: "center", fontSize: "18px", fontWeight: "bold" }}>Address:</div>
                            <div>48, Tarun Sengupta Sarani,</div>
                            <div>Dum Dum, Kolkata, West Bengal, India</div>
                            <div>700079</div>
                        </div>
                    </div>
                </div>
            </div>
            )};
        </div>
    );
}

export default List;

錯誤 :

list.jsx:19 Uncaught (in promise) TypeError: profile.map is not a function
    at List (list.jsx:19)
    at renderWithHooks (react-dom.development.js:14985)
    at updateFunctionComponent (react-dom.development.js:17356)
    at beginWork (react-dom.development.js:19063)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994)
    at invokeGuardedCallback (react-dom.development.js:4056)
    at beginWork$1 (react-dom.development.js:23964)
    at performUnitOfWork (react-dom.development.js:22776)
    at workLoopSync (react-dom.development.js:22707)
    at renderRootSync (react-dom.development.js:22670)
    at performSyncWorkOnRoot (react-dom.development.js:22293)
    at react-dom.development.js:11327
    at unstable_runWithPriority (scheduler.development.js:468)
    at runWithPriority$1 (react-dom.development.js:11276)
    at flushSyncCallbackQueueImpl (react-dom.development.js:11322)
    at flushSyncCallbackQueue (react-dom.development.js:11309)
    at scheduleUpdateOnFiber (react-dom.development.js:21893)
    at dispatchAction (react-dom.development.js:16139)
    at list.jsx:12

由於您使用異步調用來加載數據,因此您應該在顯示列表之前檢查要獲取的profile狀態。
另外,請注意我將[]參數添加到useEffect鈎子中。
這樣 get 調用只會在組件被渲染時執行。

嘗試像這樣更改您的代碼:

const List = () => {
  const [profile, setData] = useState([]);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
        const { data } = await axios.get('https://randomuser.me/api/?results=50');
        setData(data);
    } catch (err) {
        console.log(err)
    }
  };

  return (
    <div className='main'>
      {!profile
        ? 'Loading data...'
        : profile.map((key, value) => (
            <div className='listCard'>
              <div className='userName'>
                <div style={{ margin: '10px 0 10px 20px' }}>
                  Username : {profile[value].login.username}
                </div>
              </div>
              <div className='details'>
                <div className='topDetails'>
                  <div className='nameAndEmail'>
                    <div style={{ fontSize: '25px', fontWeight: 'bold' }}>
                      Mr Siddhartha Chatterjee
                    </div>
                    <div
                      style={{
                        fontSize: '20px',
                        color: 'rgb(128, 128, 112)',
                        marginTop: '20px',
                      }}
                    >
                      Email: siddc.8@gmail.com
                    </div>
                  </div>
                  <div className='picture'>
                    <div className='imageBox'></div>
                  </div>
                </div>
                <div className='bottomDetails'>
                  <div className='nationality'>
                    <div style={{ fontWeight: 'bold', fontSize: '22px' }}>
                      User for 6 years
                    </div>
                    <div style={{ fontSize: '20px', marginBottom: '8px' }}>
                      Age: 25
                    </div>
                    <div style={{ fontSize: '20px', marginBottom: '8px' }}>
                      Nationality: Indian
                    </div>
                    <div style={{ fontSize: '18px', marginBottom: '8px' }}>
                      #: 9073030038
                    </div>
                  </div>
                  <div className='address'>
                    <div
                      style={{
                        textAlign: 'center',
                        fontSize: '18px',
                        fontWeight: 'bold',
                      }}
                    >
                      Address:
                    </div>
                    <div>48, Tarun Sengupta Sarani,</div>
                    <div>Dum Dum, Kolkata, West Bengal, India</div>
                    <div>700079</div>
                  </div>
                </div>
              </div>
            </div>
          ))}
      ;
    </div>
  );
};

export default List;

您是否檢查了 API 返回的結果? 它返回看起來像這樣的東西

{
    "results": [...],
    "info": {
        "seed": "574cecafce235b8c",
        "results": 50,
        "page": 1,
        "version": "1.3"
    }
}

由於您正在執行profile.map ,我假設profile應該是一個列表。 從 API 返回的res.data是一個具有屬性resultsinfo的對象,其中results可能是您要查找的數據。 要修復您的錯誤,您應該將res.data.results傳遞給setData函數而不是res.data

useEffect(() => {
    axios.get("https://randomuser.me/api/?results=50").then(
        res => {
            console.log(res.data);
            setData(res.data.results);
            console.log(profile);
        }
    )
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM