简体   繁体   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

I get the above error every time I try fetching data from a third-party API source( https://randomuser.me/api/?results=50 ) using Axios.每次尝试使用 Axios 从第三方 API 源( https://randomuser.me/api/?results=50 )获取数据时,都会出现上述错误。 The problem seems to be with the profile.map() function because when I console.log the response received from Axios, it displays all the data.问题似乎出在profile.map()函数上,因为当我 console.log 从 Axios 收到的响应时,它会显示所有数据。 You would find the profile.map() function on the list.jsx element right at the start of return.您会在返回开始处的list.jsx元素上找到profile.map()函数。 I have seen the previous solutions and am pretty sure that I have done almost everything that was suggested in those.我已经看过以前的解决方案,并且很确定我已经完成了其中建议的几乎所有内容。 Here's the code:这是代码:

screen.jsx displays the list: 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;

list.jsx列表.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;

The error :错误 :

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

Since you are using an async call to load your data, you should check for the profile state to be fetched before displaying the list.由于您使用异步调用来加载数据,因此您应该在显示列表之前检查要获取的profile状态。
Also, note that I added the [] parameter to the useEffect hook.另外,请注意我将[]参数添加到useEffect钩子中。
This way the get call will be executed only when the component is rendered.这样 get 调用只会在组件被渲染时执行。

Try to change your code like this:尝试像这样更改您的代码:

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;

Did you check the results the API returned?您是否检查了 API 返回的结果? It returns something that looks like this它返回看起来像这样的东西

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

Since you are doing profile.map , I am assuming that profile should be a list.由于您正在执行profile.map ,我假设profile应该是一个列表。 res.data returned from the API is an object with properties results and info , where results is probably the data you're looking for.从 API 返回的res.data是一个具有属性resultsinfo的对象,其中results可能是您要查找的数据。 To fix your error, you should pass res.data.results into the setData function instead of res.data要修复您的错误,您应该将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