获取时片状错误&使用React钩渲染数据

发布于 2025-01-24 13:02:23 字数 1516 浏览 5 评论 0原文

我正在获取API&渲染结果。这已经工作了一段时间&然后,我会收到以下错误:itemlist.js:23 Uncover typeError:items.map不是函数&另外,考虑在树上添加错误边界以自​​定义错误处理行为。

关于为什么会发生的任何想法?

这是我的代码示例:

import React, { useEffect, useState } from "react";

const ItemList = () => {
    const [items, setItem] = useState("");

    useEffect(() => {
        const url = "<redacted-api-endpoint>";

        const fetchData = async () => {
            try {
                const response = await fetch(url);
                const json = await response.json();

                return setItem(json.data);
            } catch (error) {
                console.log("error", error);
            }
        };

        fetchData();
    }, []);

    return (
        <>
            {
                items.map((item, index) => {
                    const { name, title, description, image, price } = item;

                    return (
                        <div key={index}>
                            <img src={image} alt="item" width="100" height="auto" />
                            <p>{name}</p>
                            <p>{title}</p>
                            <p>{description}</p>
                            <p>{price}</p>
                        </div>
                    )
                })
            }
        </>
    );
};

export default ItemList;


I'm fetching data from an API & rendering the results. This is working for a while & then I'm getting the following error: itemList.js:23 Uncaught TypeError: items.map is not a function & also Consider adding an error boundary to your tree to customize error handling behavior.

Any ideas on why is this happening?

This is my code sample:

import React, { useEffect, useState } from "react";

const ItemList = () => {
    const [items, setItem] = useState("");

    useEffect(() => {
        const url = "<redacted-api-endpoint>";

        const fetchData = async () => {
            try {
                const response = await fetch(url);
                const json = await response.json();

                return setItem(json.data);
            } catch (error) {
                console.log("error", error);
            }
        };

        fetchData();
    }, []);

    return (
        <>
            {
                items.map((item, index) => {
                    const { name, title, description, image, price } = item;

                    return (
                        <div key={index}>
                            <img src={image} alt="item" width="100" height="auto" />
                            <p>{name}</p>
                            <p>{title}</p>
                            <p>{description}</p>
                            <p>{price}</p>
                        </div>
                    )
                })
            }
        </>
    );
};

export default ItemList;


如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

薄情伤 2025-01-31 13:02:23

useFeffect(回调,依赖项)用于在安装组件后运行的侧面效应钩,它管理功能组件中的副作用。回调参数是放置副作用逻辑的函数。依赖项是您的副作用的依赖项列表:为道具或状态值。 usefeffect(回调,依赖项) 初始安装之后调用回调 ,以及以后的渲染,如果依赖项内部有任何值。

在您的第一个/初始渲染中,该组件以其初始状态为const [item,setItem] = usestate(“”);,并且您正在通过一个空字符串进行映射。

解决方案:

考虑添加简短的电路,或在初始状态中添加项目以防止错误。

    <>
            {
                items && items.map((item, index) => {
                    const { name, title, description, image, price } = item;

                    return (
                        <div key={index}>
                            <img src={image} alt="item" width="100" height="auto" />
                            <p>{name}</p>
                            <p>{title}</p>
                            <p>{description}</p>
                            <p>{price}</p>
                        </div>
                    )
                })
            }
        </>

快速查看有关使用效果

useEffect(callback, dependencies) is for side-effects hook that runs after the component is mounted, it manages the side-effects in functional components. callback argument is a function to put the side-effect logic. dependencies is a list of dependencies of your side-effect: being props or state values. useEffect(callback, dependencies) invokes the callback after initial mounting, and on later renderings, if any value inside dependencies has changed.

In your first/initial render, the component is mounted with it's initial state which is const [items, setItem] = useState(""); and you are maping over an empty string.

Solution:

consider adding short circuiting, or add item in your initial state to prevent the error.

    <>
            {
                items && items.map((item, index) => {
                    const { name, title, description, image, price } = item;

                    return (
                        <div key={index}>
                            <img src={image} alt="item" width="100" height="auto" />
                            <p>{name}</p>
                            <p>{title}</p>
                            <p>{description}</p>
                            <p>{price}</p>
                        </div>
                    )
                })
            }
        </>

take a quick look at official react docs concerning useEffect hook

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文