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