简体   繁体   中英

I got a key error after entering a comment. I don't know how to fix (react propblem)

I got a key error after entering a comment. But I can't find a reason.

Problem: Screen flashes after comment I get a key error and can't figure out where the key error is.

Here's how I tried to fix the key error:

key = {c} => key = {c.id}

What causes a key error?

error message is this:

VM152 _app.js:22355 Uncaught TypeError: Cannot read property 'key' of undefined
    at List._this.renderItem (VM152 _app.js:22355)
    at VM152 _app.js:22465
    at Array.map (<anonymous>)
    at List._this.renderList (VM152 _app.js:22464)
    ...

code is this

const Home = () => {
    const dispatch = useDispatch();
    const { isLoggedIn, me } = useSelector(state => state.user);
    const { mainPosts } = useSelector(state => state.post);

    useEffect(() => {
        // alert("LOAD_MAIN_POSTS_REQUEST 실행")
        dispatch({
            type: LOAD_MAIN_POSTS_REQUEST,
        })
    }, []);

    return (
        <>
            {me && <PostForm />}
            {mainPosts.map((c) => {
                return (
                    <PostCard key={c.id} post={c} />
                );
            })}
        </>
    );
};

The first time the Home component renders the mainPosts array may not have any data, after useEffect is called and your action is dispatched the data will be present. To account for the data not being there on intial render you can validate mainPosts to check for null or undefined. That way the.map will only take place when mainPosts is truthy.

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