reactjs JSON中的数组在提取后未定义

piah890a  于 2023-01-08  发布在  React
关注(0)|答案(1)|浏览(147)

我想获取JSON中的所有数据,其中有两个数组。其余的数据都正确获取,但当涉及到数组时,我得到“user.category is undefined”或“user.top_media is undefined”。我该如何解决这个问题?
如果我在return语句中删除HTML,console.log(响应)将返回成功。

import React from 'react';
import './influencerProfileCard.css';
import { useState, useEffect } from 'react';
import { InstagramEmbed } from 'react-social-media-embed';    

const InfluencerProfileCard = () => {

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

    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const x = urlParams.get('influencer');    

    useEffect(() => {
      fetchUsers();
    }, []); 
  
    async function fetchUsers() {
        const response = await 
            fetch(`http://localhost:3001/api/tours/${x}`)
                .then((res) => res.json())
                .then((user) => user.data.tour)
    
      console.log(response);
      setUser(response);
    }

    return (
        <div className="infProfCard-container">

            <div className='infProfCard-info'>
                {user.category.map(c => (
                    <h4>{c}</h4>
                ))}
            </div>

            <div style={{ display: 'flex', justifyContent: 'center' }}>
                <InstagramEmbed url={user.top_media[0].media_url} width={328} captioned />
            </div>

            </div>
    )
}

export default InfluencerProfileCard

下面是我在浏览器上直接输入API时的JSON文件:

以下是控制台输出:

js81xvg6

js81xvg61#

数据没有问题,但是useState是异步的,因此您需要在获取中包含setState并等待此状态,否则React将尝试在使用数据更新状态之前呈现页面状态(为空[])。

更新:您可能还需要首先检查响应中的标记ok,因为请求可能会因404或500 HTTP错误而失败,获取将履行承诺,但结果可能不是JSON,如下所示:

const [user, setUser] = useState([]); // make sure the initial state is an empty array.
    
    useEffect(() => {
      fetchUsers();
    }, []); 
  
    async function fetchUsers() {
      try {
        const response = await fetch(`http://localhost:3001/api/tours/${x}`);
            if(!response.ok)
              throw new Error(`HTTP error ${response.status}`); 
              const user = await response.json() //parse to json only if the response statut is 200
            setUser(user.data.tour);
      } catch (err) {
        console.log(err)
      }
    };

你也可以添加一个加载页面,看到加载页面会有更好的用户体验,这是一个简单的例子:

const [user, setUser] = useState([]); // make sure the initial state is an empty array.
const [loading, setLoading] = useState(false);
   
    useEffect(() => {
      async function fetchUsers() {
        setLoading(true);
      try {
        const response = await fetch(`http://localhost:3001/api/tours/${x}`);
            if(!response.ok)
              throw new Error(`HTTP error ${response.status}`); 
              const user = await response.json() 
              setUser(user.data.tour);
      } catch (err) {
        console.log(err)
      } finally {
        setLoading(false);
      }
     }
      fetchUsers();
    }, []); 

    if (loading) {
      return <h1>User is loading...</h1>;
    } 
    return (
      <div className="infProfCard-container">
          <div className='infProfCard-info'>
              {user.category.map(c => (
                  <h4>{c}</h4>
              ))}
          </div>
          <div style={{ display: 'flex', justifyContent: 'center' }}>
              <InstagramEmbed url={user.top_media[0].media_url} width={328} captioned />
          </div>
      </div>
    )

相关问题