[英]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.