繁体   English   中英

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

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

我是 React 新手,我遇到了问题。 如何遍历数组中的数组? 尝试使用 map() 方法迭代数组时,会发生错误

我的代码:

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

import Header from '../modules/header/header';
import Footer from '../modules/footer/footer';

import './pages.scss';

function PageWorksItem({ match, location }) {

    const { params: { id } } = match;
    const [error, setError] = useState(null);
    const [isLoaded, setIsLoaded] = useState(false);
    const [works, setItems] = useState([]);

    useEffect(() => {
        let cleanupFunction = false;
        fetch(`http://localhost:3001/works/${id}`)
            .then(res => res.json())
            .then(
                (result) => {
                    console.log(result);
                    setIsLoaded(true);
                    if(!cleanupFunction) setItems(result);
                },
                (error) => {
                    setIsLoaded(true);
                    setError(error);
                }
            )
            return () => cleanupFunction = true;
        }, [])

        if (error) {
            return <div className="works error">Error: {error.message}</div>;
        } else if (!isLoaded) {
            return <div className="works loading">. . .</div>;
        } else {
            return (
                <>
                    <Header />
                    <div className="works item">
                        {works.tags.map(item => (
                            <li>{item}</li>
                        ))}
                    </div>
                    <Footer />
                </>
            );
        }
    }

export default PageWorksItem;

JSON 片段:

{
    "works": [
        { 
            "id": 1, 
            "name": "21 one line SPA images",
            "cat": "Illustrations",
            "tags": ["one", "two", "free"]
        }
    ]
}

如果您指定 {works.tags} 或使用索引 {works.tags[0]} - 一切正常,但如果您遍历数组,则会发生错误。

您正在使用works.tag.map 但是works的初始化值是一个空数组[]: const [works, setItems] = useState([]); . 所以works.tagundefined的并且发生了这个错误。 您可以通过添加optional chaining来解决此问题,如下所示:

{works.tags?.map((item, index)=> (
   <li key={index}>{item}</li>
))}

注意:使用map时需要在子组件中添加唯一key

暂无
暂无

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

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