简体   繁体   中英

Why I need to use && operand to check data from useState hook?

I'm new to react and don't understand 1 thing with useState hook:

import {useEffect, useState} from "react";

export default function People() {

    const [people, setPeople] = useState(null)
    useEffect(() => {
        const fetchData = async () => {
            const response = await fetch("https://jsonplaceholder.typicode.com/users")
            const data = await response.json()
            setPeople(data)
        }
        fetchData()
    }, [])

    return (

        <>
            <h1>People:</h1>
            <ul>
                {people && people.map(({id, name, email, username, phone, website}) => {
                    return (<div key={id}>
                        <li><h2>{name}</h2><p>{email}</p></li>
                        <p>{username}</p>
                        <p>{phone}</p>
                        <p>{website}</p>
                    </div>)
                })}
            </ul>
        </>)


}

Why when I delete "people &&" I get error: "Cannot read properties of null (reading 'map')". But when I check for the existence of "people" the code works.

Why is this happening? Is this a feature of the hook? Thank you!

I'm pretty new to react myself. In my short experience, I've would say setting your initial state of people to an empty array would solve this for you.

Because getting the data is happening asynchronously. The render is first trying to map people with the value of null which throws an error before it can try again

Hope this helps:)

Pass [] in the useState insted of null. Because we can not iterate loop over null datas. Your code should be look like below:

const [people, setPeople] = useState([])

Your initial people state value is null. As react component behave as asynchronous, the .map() method executed over null.

You can solve this issue by doing two method.

Method-1: people &&

Method-2: Assigning initial value as empty array for people state.

     const [people, setPeople] = useState([])

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