简体   繁体   中英

Cannot read property 'map' of undefined error. React Typescript

I have this code here. I keep getting an error:

TypeError: Cannot read property 'map' of undefined.

Here are a few facts:

  1. I get data from the front-end javascript file. So there shouldn't be any async problems.
  2. singleCategory.title Always displays correctly.
  3. The error happens only if I refresh the page. If I comment out the map code and add code. So that React could inject it without refresh. It works. I only get an error if I refresh the page or try to navigate to it. 在此处输入图像描述

Why does singleCategory.title display correctly but using map is undefined? Also map is undefined only on refresh. If code is injected it works properly.

const CoursesCategories: React.FC = () => {
    const [singleCategory, setSingleCategory] = useState<CategoriesInterface>([] as any);

    useEffect(() => {
        const fullUrl = window.location.href;
        const segments = new URL(fullUrl).pathname.split('/');
        const id = segments.pop() || segments.pop();

        for (let category of Categories ) {
            if (category.url === id) {
                setSingleCategory(category);
                console.log(singleCategory)
            }
        }
    }, [singleCategory]);


    return (
        <div>
            {
                singleCategory.courses !== [] ? (
                    <div>
                        <CategoryTitle title={singleCategory.title} />

                        <div className={wrapper.headerWrapper}>
                            {
                                singleCategory.courses.map((course: CoursesInterface) => (
                                    <h2 key={course.id}>{course.title}</h2>
                                    )
                                )
                            }
                        </div>
                    </div>
                ) : ''
            }

        </div>
    )
}

Edit 1. If I write like this I get.

Cannot read property 'length' of undefined

{ singleCategory.courses.length > 0 && singleCategory.courses.map((course: CoursesInterface) => (
                                    <h2 key={course.id}>{course.title}</h2>
                                )
                            )}

Since you're using typescript you could use optional chaining :

{ singleCategory.courses?.length > 0
    && singleCategory.courses?.map((course: CoursesInterface) => (
                                    <h2 key={course.id}>{course.title}</h2>
                                )
  )}

because at the first rendering that property is not available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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