简体   繁体   English

TypeError:无法读取未定义的属性“地图”(反应)

[英]TypeError: Cannot read property 'map' of undefined (React)

I have this code userPage that is suppose to fetch data from an online JSONplaceholder of users and output it based on ID.我有这个代码 userPage 假设从用户的在线 JSONplaceholder 和 output 它基于 ID 获取数据。 Currently my i am fetching the data correctly, but when I try to render it, I get the error "TypeError: Cannot read property 'map' of undefined" for some reason.目前我正在正确获取数据,但是当我尝试渲染它时,由于某种原因,我收到错误“TypeError:无法读取未定义的属性'map'”。 Not sure why, I feel like it is a small error but I have been racking my brain for hours trying to figure it out.不知道为什么,我觉得这是一个小错误,但我已经绞尽脑汁好几个小时试图弄清楚它。

UserPage用户页面

export const UserPage = ({match}) => {
const [data, setData] = useState({ hits: [] });

useEffect(() => {
    function getFetchUrl() {
        return `https://jsonplaceholder.typicode.com/users/${match.params.id}`;
    }

    async function fetchData() {
        const result = await axios(getFetchUrl());
        setData(result.data);
    }

    fetchData();
}, [match.params.id]);

console.log(data)
return (
    <>
        <ul>
            {data.hits.map(item => (
                <li key={item.id}>
                    <a href={item.url}>{item.title}</a>
                </li>
            ))}
        </ul>
    </>
);

} }

all of the api data is stored inside hits, but this is how the data in hits looks like when I console.log(data) after making the API call in useEffect所有 api 数据都存储在点击中,但这就是我在 useEffect 中调用 API 后 console.log(data) 时点击中的数据的样子

在此处输入图像描述

as you can see, the data is correct, but the first time it runs, hits: Array{0}.如您所见,数据是正确的,但第一次运行时,点击:Array{0}。 The data is the correct output after that call.调用后数据是正确的 output。 I feel like this might be the problem, but I'm not quite sure and I don't know how to fix it.我觉得这可能是问题所在,但我不太确定,也不知道如何解决。 Also, I'm not sure why it made the call 3 times, but I don't know if that matters either.另外,我不确定它为什么打了 3 次电话,但我也不知道这是否重要。 I am new to React.JS so I'm figuring out all these things as I go along.我是 React.JS 的新手,所以我正在弄清楚所有这些事情,因为我是 go。

Thank you!谢谢!

If you want the state to be an object, then you need to update it like one.如果您希望 state 成为 object,那么您需要像更新它一样更新它。 As per your current code, you are replacing the object in state data with what you get from api which causes your model to break根据您当前的代码,您将 state 数据中的 object 替换为您从 api 获得的内容,这会导致您的 Z20F35E630DAF394DDB8 中断

 async function fetchData() {
    const result = await axios(getFetchUrl());
    setData({hits: result.data}); // pass an object
}

Also note that state updates with hooks do not merge the state, so say you have multiple keys in the object and you would like to update only one, you need to merge and update it like另请注意,带有挂钩的 state 更新不会合并 state,因此假设您在 object 中有多个密钥,并且您只想更新一个,您需要合并和更新它

setData(prev => ({
   ...prev,
   hits: result.data
}))

Add a boolean variable, initialise it as false then set it to true once axios promise is recieved.添加一个 boolean 变量,将其初始化为false ,然后在收到 axios promise 后将其设置为true And console your data when this boolean is true.并在 boolean 为真时控制您的数据。

export const UserPage = ({match}) => {
const [data, setData] = useState({ hits: [] });
const [fetched, setFetched] = useState(false);
useEffect(() => {
    function getFetchUrl() {
        return `https://jsonplaceholder.typicode.com/users/${match.params.id}`;
    }

    async function fetchData() {
        const result = await axios(getFetchUrl());
        setData(result.data);
        setFetched(result.data && true);
    }

    fetchData();
}, [match.params.id]);

fetched && console.log(data)

i hope this will solve the error with console log.我希望这将解决控制台日志的错误。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM