在React.js中使用useState处理深层嵌套的Json对象

时间:2019-12-28 11:50:16

标签: json reactjs

我正试图从嵌套的json中获取价值。但出现“ 未定义”错误。当我在控制台中显示相同的对象时,它工作正常。我想从嵌套的json对象中获取特定字段。

这是api的json输出,我想从json下面获取用户ID,名称和已验证的字段

{
status: true,
user:
{
    id: 11362
    phone: "+918971557357"
    name: "Sagar pawar"
    email: null
    bio: null
    address: null
    date_of_birth: null
    token: "EMAWdBl3LDjl1X5veo6VvZBKfgQns5wTFXKWjIh9w4VKKXlclRo5ZBlWaJUBS5ImaVZANN9DlHSbFWquObaW1FIJLVGPqFLWKoPEzKLvZAJakhoTxg5TRTjVtLEVz9R9zAbocwF7dmRdI4GCAMlJdtKOEZAUuOcf6AZD"
    image: ""
    role: "user"
    notification_cleared: {date: "2019-12-28 11:42:34.899503", timezone_type: 3, timezone: "UTC"}
    deleted_by: null
    blocked: 0
    verified: 0
    }
}

这是我尝试过的提取功能。

fetch(url, options)
      .then(res => res.json())
      .then(body => console.log("Data Response", body))
      .then(data => {
        const jsonobj = data.user.id;
        console.log("User ID:", jsonobj);
      })

这是我尝试过的。

const [responseUserId, setUserId] = useState(userId);
...

fetch(url, options)
    .then(res => res.json())
    .then(res =>
      setUserId({ userId: res.user['id'] })
    )

提前谢谢。

3 个答案:

答案 0 :(得分:0)

我创建了一个简单的提取请求和setUserId,就像您想要的那样,它可以正常工作。

问题是您使用3,然后只需要2。 在第三个中,数据是未定义的,但是在第二个中,您具有所需的内容。

.then(res => res.json())
.then(body => console.log("Data Response", body))
.then(data => {

https://codesandbox.io/s/reverent-mestorf-o43s1

它是如此简单,希望对您有帮助

答案 1 :(得分:0)

我将在最后一个带有useState的功能组件示例中使用:

您用responseUserId初始化userId。给定您提供的代码,该代码将无法编译,因为未定义userId。给它一个值,例如null0或一个空字符串。

如果返回的对象只有一个属性,则可能不需要该对象的数据类型。在我的示例中,data.userId的类型为responseUserId

import React, { useEffect, useState } from 'react';

export default function App() {
  const [responseUserId, setResponseUserId] = useState(null);

  useEffect(() => {
    const url = 'https://jsonplaceholder.typicode.com/todos/1';
    fetch(url)
      .then(res => res.json())
      .then(data => setResponseUserId(data.userId))
      .catch(err => console.error(err));
  }, []);

  return responseUserId && <h3>{responseUserId}</h3>;
}

答案 2 :(得分:0)

首先。在记录数据的访存函数中,第二个记录不返回任何数据,因此在第三个记录中,回调参数未定义。在console.log("Data Response", body)之后,您应该添加return body,以便在下一个data语句中将其作为then传递下来。

第二,您的ID是一个字符串(或数字,没关系)。因此,您的responseUserId将是一个字符串。因此,当使用useState设置状态时,您无需传递对象,只需传递值即可。像这样:setUserId(res.user['id'])

希望这会有所帮助!