gpt4 book ai didi

Django rest framework and react Cannot read properties of undefined (reading '')(Django REST框架和Reaction无法读取未定义的属性(读取‘’))

转载 作者:bug小助手 更新时间:2023-10-27 20:02:47 30 4
gpt4 key购买 nike



I am fetching some data with react from django rest framework and put them into state. And then pass them into another component with props. When I print them I get the object and it works perfectly. For example console.log(props.user1) gets me this:

我正在使用Reaction从Django REST框架中获取一些数据,并将它们放入状态。然后使用道具将它们传递到另一个组件中。当我打印它们时,我得到了对象,它工作得很完美。例如,console.log(pros.user1)为我提供了以下内容:


Array(1)
0:
{
date_joined: 2023-09-06T16:07:37.214335Z"
email: ""
username: "t"
}
...

But when I print props.user1.username I get

但是当我打印pros.user1.username时,我得到



TypeError: Cannot read properties of undefined (reading 'username')



更多回答

you're sending it as an array, not an object

您要将其作为数组发送,而不是对象

Yeah but even when I write props.user1[0] I get `` Cannot read properties of undefined (reading '0')`` Also when I write with typeof I get object

是的,但即使当我编写pros.user1[0]时,我也会得到``无法读取未定义的属性(正在读取‘0’)``,当我使用typeof写入时,我也会得到Object

Check if props.user1 exists and if it does then props.user1[0], as it can be the case due to async nature

检查pros.user1是否存在,如果存在,则检查pros.user1[0],因为由于异步的性质,可能会出现这种情况

优秀答案推荐

it is look like:

它看起来像:


0: { date_joined: date, email: String username: String }

0:{DATE_JOINED:日期,电子邮件:字符串用户名:字符串}


if you want to get username, you have to use
props.user1.0.username
you can't use
props.user1[0]

如果你想获得用户名,你必须使用proposs.user1.0。用户名你不能使用pros.user1[0]



Well the problem was way more simple.

其实问题要简单得多。


I had defined state like this:

我是这样定义州的:


const [user,setUser] = useState()

Const[User,setUser]=useState()


instead of this

而不是这个


const [user,setUser] = useState([])

const [user,setUser] = useState([])


And I should print it like this console.log(user[0]?.username)

我应该像这样打印它。控制台日志(用户[0]?用户名)


更多回答

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com