TypeError:无法读取未定义的React Hooks的属性“ map”

萝拉

我需要一些帮助来理解为什么我从标题中得到错误:'TypeError:无法读取未定义的属性'map'。我需要在页面上(例如此处的州和国家)呈现API的一些数据,但是由于某些原因无法正常工作。

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const APIFetch = () => {
    const [user, setUser] = useState('');
    const [info, setInfo] = useState([]);

    const fetchData = async () => {
        const data = await axios.get('https://randomuser.me/api');
        return JSON.stringify(data);
    }

    useEffect(() => {
        fetchData().then((res) => {
            setUser(res)
            setInfo(res.results);
        })
    }, [])

    const getName = user => {
        const { state, country } = user;
        return `${state} ${country}`
    }

    return (
        <div>
            {info.map((info, id) => {
                return <div key={id}>{getName(info)}</div>
            })}
        </div>
    )
}

你们能帮我些忙吗?谢谢。

英国沙伦

试试这个方法

const APIFetch = () => {
  const [user, setUser] = useState("");
  const [info, setInfo] = useState([]);

  const fetchData = async () => {
    const data = await axios.get("https://randomuser.me/api");
    return data;  <--- Heres is the first mistake
  };

  useEffect(() => {
    fetchData().then((res) => {
      setUser(res);
      setInfo(res.data.results);
    });
  }, []);

  const getName = (user) => {
    const { state, country } = user.location;  <--- Access location from the user
    return `${state} ${country}`;
  };

  return (
    <div>
      {info.map((info, id) => {
        return <div key={id}>{getName(info)}</div>;
      })}
    </div>
  );
};
  1. 返回时data不带字符串化fetchData
  2. 进入user.location内部getName

基本代码-https://codesandbox.io/s/sharp-hawking-6v858?file=/src/App.js

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

React Jest:TypeError:无法读取未定义的属性“ map”

TypeError:无法读取未定义的React Native的属性'map'

使用React Hooks获取数据-无法读取未定义的属性“ map”

TypeError:无法读取未定义的属性“ map”

反应TypeError:无法读取未定义的属性'map'

ReactJS:TypeError:无法读取未定义的属性“ map”

TypeError:无法使用ReactJs读取未定义的属性“ map”

无法读取未定义的TypeError属性“ map”

TypeError:无法读取reactjs中未定义的属性'map'

TypeError:无法读取未定义的Reactjs的属性“ map”

TypeError:无法读取未定义<Angular 8>的属性'map'

ReactJs-TypeError:无法读取未定义的属性“ map”

TypeError:无法读取未定义的Reactjs的属性“ map”?

TypeError:无法读取未定义React.js的属性“ map”

React.js错误:TypeError:无法读取未定义的属性'map'

Uncaught TypeError:无法读取未定义的属性“ map”-React js

`TypeError:无法读取功能组件中React中未定义的属性'map'

Uncaught TypeError:无法使用React读取未定义的属性“ map”

TypeError:无法读取react-redux中未定义的属性'map'

React组件迭代数据行:TypeError:无法读取未定义的属性“ map”

TypeError:无法读取React Native中未定义的属性'map

React + Axios:未捕获(承诺)TypeError:无法读取未定义的属性“map”

React / MaterialUI-TypeError:无法读取未定义的属性“ map”

TypeError:无法读取未定义的React Native Redux的属性'map'

React-Redux 搜索栏错误 דTypeError:无法读取未定义的属性‘map’”

React TypeError:无法通过传递的道具读取未定义的属性“ map”

如何修复'TypeError:无法在React中读取未定义的属性'map'

TypeError:无法读取react.js中未定义的属性'map'

React-Redux TypeError:无法读取未定义的属性“map”