Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

reactjs - Error with Mapping array React Typescript

I'm creating a list of things but it gives me the same error the whole time. that the .map function won't work on my Variable so can you guys help me out.

It's made in Typescript React. I was trying to get this to work for a hole week and still can't find the problem I even tried rewriting the hole system but still didn't work so this is my last hope.

Error

react-dom.development.js?e444:25163 Uncaught TypeError: Cannot read property 'map' of undefined
    at _default (CloudServersContainer.tsx?a799:46)
    at renderWithHooks (react-dom.development.js?e444:16240)
    at mountIndeterminateComponent (react-dom.development.js?e444:18774)
    at beginWork$1 (react-dom.development.js?e444:20136)
    at HTMLUnknownElement.callCallback (react-dom.development.js?e444:337)
    at Object.invokeGuardedCallbackDev (react-dom.development.js?e444:386)
    at invokeGuardedCallback (react-dom.development.js?e444:441)
    at beginWork$$1 (react-dom.development.js?e444:25737)
    at performUnitOfWork (react-dom.development.js?e444:24664)
    at workLoopSync (react-dom.development.js?e444:24637)

The Json that I get when I do Eggs.data

Link to the image: https://i.imgur.com/EA8UVBd.png

The Code:

import React, { componentDidMount, useEffect, useState } from 'react';
import PageContentBlock from '@/components/elements/PageContentBlock';
import Button from '@/components/elements/Button';
import Input from '@/components/elements/Input';
import InputSpinner from '@/components/elements/InputSpinner';
import tw from 'twin.macro';
import useSWR from 'swr';
import TitledGreyBox from '@/components/elements/TitledGreyBox';
import { Textarea } from '@/components/elements/Input';

export default () => {
    const [loading, setLoading] = useState(false);

    interface EggsPlace {
        Egg: String;
        run(arg: any): void;
    }

    const [Eggs, setEggs] = useState<EggsPlace>([]);

    const getEggs = async () => {
        const response = await fetch('/api/client/cloudservers/getoptions');
        if (response.status !== 400) {
            const content = await response.json();
            const data = content;
            setEggs({ data });
        }
    };

    useEffect(() => {
        getEggs();
    }, []);

    if (typeof Eggs.data !== 'undefined') {
        console.log(Eggs.data[0]);
    }



    return (
        <PageContentBlock title={'Options'} showFlashKey={'options'}>
            <h1>Server Types:</h1>
            <div css={tw`w-full grid grid-flow-col grid-rows-2 grid-cols-3 gap-4`}>
                {
                    Eggs.data !== 'undefined' ?
                        Eggs.data.map(item => (
                            console.log(item)
                        ))
                        :
                        <p>loading</p>
                }
            </div>
            <TitledGreyBox title="Configuration" css={tw`flex-wrap md:flex-no-wrap`}>
                <div css={tw`w-full grid grid-flow-col grid-rows-2 grid-cols-2 gap-4`}>
                    <div css={tw`w-full col-span-2`}>
                        <InputSpinner visible={loading}>
                            <Input
                                readOnly={false}
                                name={"Name"}
                                placeholder={"Name Server"}
                            />
                        </InputSpinner>
                    </div>
                    <InputSpinner visible={loading}>
                        <Input
                            readOnly={false}
                            name={"Memory"}
                            placeholder={"Memory"}
                        />
                    </InputSpinner>
                    <InputSpinner visible={loading}>
                        <Input
                            readOnly={false}
                            name={"Disk"}
                            placeholder={"Disk"}
                        />
                    </InputSpinner>
                </div>
                <div css={tw`mt-4 w-full`}>
                    <Textarea
                        placeholder={'Description'}
                    />
                </div>
            </TitledGreyBox>
            <Button css={tw`mt-4`} color="primary">Create Server</Button>
        </PageContentBlock>
    );
};
question from:https://stackoverflow.com/questions/65865502/error-with-mapping-array-react-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I believe that the issue is here:

Eggs.data !== 'undefined'

this is comparing to a string 'undefined'.

What you want is Eggs.data !== undefined or !Eggs.data or typeof Eggs.data !== 'undefined'

Also, you have some TypeScript issues I believe, if you do:

setEggs({ data });

Then you should initialize Eggs like this

    const [Eggs, setEggs] = useState<{data: EggsPlace[]}>({data: []});

That would also make sure your initialise data with an empty array. Although, it would still break if data in setEggs({ data }); is not an array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...