简体   繁体   English

无法读取未定义的属性 'xxx' - 使用 axios

[英]Cannot read property 'xxx' of undefined - using axios

I've got issues accesing some of the data returned by api.我在访问 api 返回的一些数据时遇到问题。 When I assign data using setPosts(data) like this当我像这样使用 setPosts(data) 分配数据时

useEffect(() => {


   axios.get("https://api.randomuser.me/")
   .then(res => {
     console.log(res)
     const data = res.data.results["0"]
     setPosts(data) })




 },[])

into here: const[posts,setPosts] = useState({data: []})进入这里: const[posts,setPosts] = useState({data: []})

I can use this in <div>{posts.gender}</div>我可以在<div>{posts.gender}</div>中使用它

But when I try to go one step lower, <div>{posts.name.first}</div> , I get the error as in the title.但是,当我尝试将 go 降低一步<div>{posts.name.first}</div>时,我得到了标题中的错误。 When I check the console, I can see all the data is there.当我检查控制台时,我可以看到所有数据都在那里。

Thank you谢谢

In your effect, you're setting an object that describes a user to your state posts , eg在您的效果中,您正在设置一个 object 来描述您的 state posts的用户,例如

{
  gender: "female",
    name: {
    title: "Miss",
    first: "Nicoline",
    last: "Løvli"
  },
  location: {
  ...
}

However when you create your state in const[posts,setPosts] = useState({data: []}) - you're setting an object {data: []} to posts as a default value.但是,当您在const[posts,setPosts] = useState({data: []})中创建 state 时 - 您将posts {data: []}设置为默认值。

During your first render, the user's data is not retrieved yet from request, so the component is still using {data: []} .在您的第一次渲染期间,尚未从请求中检索到用户的数据,因此该组件仍在使用{data: []}

When <div>{posts.gender}</div> is rendered - it is not failing because in this case posts.gender value is just undefined - you're trying to access field gender from object {data: []} .<div>{posts.gender}</div>被渲染时——它并没有失败,因为在这种情况下posts.gender值只是undefined ——你试图从 object {data: []}访问字段gender So it renders an empty div .所以它呈现一个空的div

At the same time when <div>{posts.name.first}</div> tries to render - posts.name is also just undefined and you're basically trying to access field first from undefined .同时,当<div>{posts.name.first}</div>尝试渲染时, posts.name也只是undefined ,您基本上是在尝试从undefined first访问字段。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM