简体   繁体   English

为什么我需要使用 && 操作数来检查来自 useState 钩子的数据?

[英]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:我是新手,不了解 useState 钩子的一件事:

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')".为什么当我删除“people &&”时出现错误:“无法读取 null 的属性(读取‘地图’)”。 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.根据我的短暂经验,我会说将您最初的 state 人设置为空数组可以为您解决这个问题。

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渲染首先尝试使用值为 null 的 map 人,这会在重试之前抛出错误

Hope this helps:)希望这可以帮助:)

Pass [] in the useState insted of null. Because we can not iterate loop over null datas.在 null 的 useState insted 中传递 []。因为我们无法迭代循环 null 数据。 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.您最初的people state 值为 null。由于 React 组件表现为异步, .map()方法在 null 上执行。

You can solve this issue by doing two method.您可以通过两种方法解决此问题。

Method-1: people &&方法一: people &&

Method-2: Assigning initial value as empty array for people state.方法二:给state人赋初值空数组。

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

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

相关问题 在 useState Hook 中使用 SWR 数据 - use SWR data in useState Hook 为什么我不能从当前的 state 中获取一个值并在我的 useState 挂钩中使用它? - Why cant I take a value from the current state and use that inside of my useState hook? 更新时在对象上使用 useState 挂钩时是否需要使用扩展运算符? - Do I need to use the spread operator when using useState hook on object when updating? 这是在使用状态挂钩时获取数据的正确方法吗? 我使用 usestate hook 但我不知道这是否是获取数据的正确方法 - is this the right way to fetch data while usine usestate hooks? i use usestate hook but i don't know if this the right way to fetch data 为什么在 React 中尝试使用 useState 挂钩时出现“未定义”? - Why am I getting 'undefined' when trying to use the useState hook in React? 如何在 useState 中使用从 DB 获取的数据? - How do I use data that I fetched from DB in useState? 如果我在React useState钩子中对状态进行突变,为什么会很重要? - Why does it matter if I am mutating state in React useState hook? 如何使用 useState 挂钩到 map JSON 来自 API 的响应 - How to use useState hook to map JSON response from API 我无法通过 useState 钩子从 FlatList 中删除项目 - I can't remove items from FlatList by useState hook 从孩子访问 useState 钩子 - Accessing useState hook from child
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM