【问题标题】:Undefined is not an object while trying to query nested objects. Using axios and React尝试查询嵌套对象时,未定义不是对象。使用 axios 和 React
【发布时间】:2020-12-03 17:01:13
【问题描述】:

JSON 响应如图 1 所示。
我能够使用 axios(已经使用 JSON.parse)将整个响应分配给状态(命名配置文件)。

profile.bioprofile.image 工作时;
profile.user.username 等不工作并抛出错误 - Undefined is not an object

const [profile, setProfile] = useState({});
const phone_no = phone.phone;
const fetchProfile = useEffect(() => {
var res = {};

axios
  .get('<API URL>' + phone_no)
  .then((response) => (res = response.data))
  .then(() => {
    setProfile(res);
  })
  .then(() => console.log(profile))
  .catch((e) => console.log(e)); });



const user_stream = {
    name: first.first_name,
    image: profile.image,
    id: profile.user.id,
  };

更新 - 解决方案:将 async-await 与 axios 一起使用,已修复。

【问题讨论】:

  • 使用您发布的图像上的数据,它应该可以工作...或发布您的代码以检查是否存在错误
  • 请将代码示例放在帖子正文中,不要作为图片链接。
  • 添加的代码,见 user_stream - image: profile.image 正在工作;但不是 id:profile.user.id
  • 这个问题(现在?)令人困惑,因为它引用了一个 image 1,但没有。

标签: javascript json reactjs react-native axios


【解决方案1】:

profileprofile.user 在尝试访问时可能仍然未定义,因此 profile.bio 只是未定义,因此不会导致错误,但 profile.user.username 尝试访问未定义对象的属性。

尝试添加profile?.user?.username

profile &amp;&amp; profile.user &amp;&amp; profile.user.username

这将确保它仅在配置文件已定义的情况下尝试呈现用户名

【讨论】:

  • profile.bio 起作用,因为profile is instantiated as an empty object so while the actual profile is being fetched profile.bio` 将返回 undefined 并且反应不会在那一瞬间渲染任何东西,然后一旦返回实际配置文件,bio 就会像现在一样填充@987654330 @ 有一个值,但是如果您尝试访问 profile.user.username 而 profile 仍然是一个空对象,则会引发错误,因为您正在尝试访问未定义对象 userusername 属性,因为它还不存在在profile 对象上。我希望这是有道理的
  • 是的,明白你的意思。
猜你喜欢
  • 2021-12-14
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多