简体   繁体   English

使用 useEffect 调用 API。 当尝试映射用户时,它说 TypeError: Cannot read property 'map' of undefined

[英]Calling an API With useEffect . when Trying to mapping user it is saying TypeError: Cannot read property 'map' of undefined

import logo from './logo.svg';
import './App.css';
import { useEffect, useState } from 'react';
import User from './components/User/User';

function App() {
  const [user, setUser] = useState([]);
  useEffect(() => {
    // Create an scoped async function in the hook
    async function loadData() {
      const response = await fetch("https://randomuser.me/api/?results=10");
      const data = await response.json();
      setUser(data.results);
    }

    loadData()
  }, [])

  console.log(user)

  return (
    

    
    <div className="App">
      <ul>
          {

            user && user.results.map(usr => <User user={usr}></User>)
          }
      </ul>
     
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

I am Calling the API with useEffect.我正在使用 useEffect 调用 API。 Before that I have set a const with useState named user with a default value of empty array.在此之前,我使用 useState 命名用户设置了一个 const,其默认值为空数组。 In useEffect I set user value with setUSer().在 useEffect 中,我使用 setUSer() 设置用户值。 But when I am mapping user it is giving mean error with a message TypeError: Cannot read property 'map' of undefined;但是当我映射用户时,它给出了一条消息 TypeError: Cannot read property 'map' of undefined; 的平均错误。

Seems unlikely that you'd need both setUser(data.results) and user.results.map - that's like data.results.results.map .您似乎不太可能同时需要setUser(data.results)user.results.map - 这就像data.results.results.map I think you want user.map , and then you can drop the user && check too, because .map will still work on the empty array.我想你想要user.map ,然后你也可以删除user &&检查,因为.map仍然可以在空阵列上工作。

put a conditional rendering for the results.为结果添加条件渲染。 this happens because the api fetch takes time and until then ur user variable is undefined.发生这种情况是因为 api 提取需要时间,并且在此之前您的user变量是未定义的。

If you check empty array as "user &&", it'll still give true.如果您将空数组检查为“用户&&”,它仍然会为真。

Try to check user.length > 0 or isEmpty(user) from lodash/underscore.尝试从 lodash/underscore 检查user.length > 0isEmpty(user)

user.length > 0 && user.results && user.results.map(usr => <User user={usr}></User>)

as you can see, your fetching an api with Array Name: results.如您所见,您获取的 api 与 Array Name: 结果。 this is the link:- https://randomuser.me/api/?results=10 so your setting the user to be the data.results.这是链接:- https://randomuser.me/api/?results=10所以您将用户设置为 data.results。 and then accessing user.results.map, and thats wrong because you dont have results in user, the user values equal to results.values然后访问 user.results.map,这是错误的,因为您在用户中没有结果,用户值等于 results.values

solution:- 1- change from user.results.map to -> user.map here how it will be:-解决方案:- 1- 从 user.results.map 更改为 -> user.map 这里将如何:-

import logo from './logo.svg';
import './App.css';
import { useEffect, useState } from 'react';
import User from './components/User/User';

function App() {
  const [user, setUser] = useState([]);
  useEffect(() => {
    // Create an scoped async function in the hook
    async function loadData() {
      const response = await fetch("https://randomuser.me/api/?results=10");
      const data = await response.json();
      setUser(data.results);
    }

    loadData()
  }, [])

  console.log(user)

  return (
    

    
    <div className="App">
      <ul>
          {

            user && user.map(usr => <User user={usr}></User>)
          }
      </ul>
     
 

暂无
暂无

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

相关问题 类型错误:当我尝试访问 API 调用数据时,无法读取未定义的属性“映射” - TypeError: Cannot read property 'map' of undefined when I am trying to access API call data “TypeError:使用 useState 和 useEffect 时无法读取未定义的属性‘名称’” - “TypeError: Cannot read property 'name' of undefined” when using useState and useEffect Google App 脚本 - 映射时出错 - TypeError:无法读取未定义的属性“地图” - Google App Script - Error when Mapping - TypeError: Cannot read property 'map' of undefined 反应useEffect无法读取未定义的属性'map' - React useEffect Cannot read property 'map' of undefined 当基于用户输入调用get实体时,“ Uncaught TypeError:无法读取未定义的属性&#39;read&#39; - when calling the get entity based on user input ,"Uncaught TypeError: Cannot read property 'read' of undefined 类型错误:尝试使用本地存储而不是使用状态时无法读取未定义的属性“地图” - TypeError: Cannot read property 'map' of undefined when trying to useLocalStorage instead of useState 尝试使用 function 的结果时出错,typeError: Cannot read property 'map' of undefined in React - Error when trying to use the result of a function, typeError: Cannot read property 'map' of undefined in React 类型错误:调用“firebase.auth().onAuthStateChanged((user)”时无法读取未定义的属性“auth” - TypeError: Cannot read property 'auth' of undefined when calling " firebase.auth().onAuthStateChanged((user)" 类型错误:从 API 调用时无法读取未定义的属性(读取“地图”) - TypeError: Cannot read properties of undefined (reading 'map') when calling from an API 未捕获到的TypeError:无法读取Google Map API中未定义的属性“ PlacesService” - Uncaught TypeError: Cannot read property 'PlacesService' of undefined in google map api
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM