django 获取嵌套API数据到reactjs

gopyfrb3  于 2023-05-30  发布在  Go
关注(0)|答案(1)|浏览(107)

我在获取下面提供的API数据时遇到空白显示。我如何修改我的代码以在React中显示这些嵌套数据

[
    {
        "pk_id": "HTR4q",
        "name": " Contagious Bovine Pleuropneumonia(CBPP)",
        "species": "cattle",
        "language": "en-uk",
        "translations": {
            "en-uk": {
                "subcategory": "Diseases with respiratory/breathing signs",
                "subcategory_desc": "Diseases described in this section are those that have respiratory/breathing signs as the main indication of illness. These include Contagious Bovine Pleuropneumonia and East Coast fever.",
                "name": "Contagious Bovine Pleuropneumonia (CBPP)",
                "local_names": "Somali Berfur, Sambab\r\nBorana Sombes\r\nRendille Argab Looyo\r\nSamburu Lkipei, Loonkishu\r\nTurkana Loukoi Angaatuk\r\nGabra Sombes",
                "other_livestock_affected": "It affects cattle only.",
                "transmission": "Susceptible cattle become infected by inhalation of droplets from an affected animal. Urine droplets from a sick animal can also transmit the disease. Transmission can occur even if a healthy animal is between 20 to 200 metres away from an infected one.",
                "distribution": "",
                "number_affected": "In unexposed populations, up to 100% are affected. In areas where the disease is common, 10–60% of the animals are affected.",
                "death_rate": "In unexposed populations, the disease can kill more than 50% of the animals. In areas where the disease is common, less than 10% of the– animals die from the disease.",
                "predisposing_factors": "Occurs in all seasons\r\nLivestock movement – mixing of herds at watering points and on grazing fields\r\nPresence of susceptible animals\r\nSub clinical or carrier animals in the herd",
                "key_signs": "Rocking body back and forth while breathing, with some grunting—breathing is shallow and rapid \r\nDry cough upon exercise\r\nStanding with arched back, elbows out and head and neck extended\r\nAnimal faces the wind with its nostrils wide open (dilated)",
                "dead_animal_signs": "",
                "other_signs": "Animal seeks shade\r\nNasal discharge \r\nDepression\r\nLags behind as the herd moves\r\nEmaciation \r\nTearing",
                "prevention": "Separate infected animal \r\nIsolate affected herds \r\nControlled livestock movement\r\nBiannual vaccination\r\nMake sure introduced animals into your herd are healthy—seek veterinary advice",
                "human_prevention": "",
                "human_management": "",
                "zoonotic_potential": null
            }]

这是我的Jsx代码,用于获取和Map数据,但内容在各种转换下,例如。en-uk无法显示。如果有人能帮我解决我正在解决的问题,那就太好了。先谢谢你了。

const Home = () => {
  const [diseaseData, setDiseaseData] = useState(null);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const response = await fetch("http://127.0.0.1:8000/api/disease/");
      const data = await response.json();
      setDiseaseData(data);
      console.log(data);
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

 

  const getTranslation = (langCode) => {
    if (diseaseData && diseaseData.translations) {
      return diseaseData.translations[langCode] || null;
    }
    return null;
  };

  console.log("Rendering"); // Debugging console log
  console.log("diseaseData:", diseaseData);
  console.log(
    "translations keys:",
    diseaseData && Object.keys(diseaseData.translations || {})
  );
  return (
    <div>
      {diseaseData &&
        diseaseData.translations &&
        Object.keys(diseaseData.translations).map((langCode) => {
          const translation = getTranslation(langCode);
          if (!translation) {
            return null; // Skip if translation is not available
          }
          return (
            <div key={langCode}>
              <h2>{translation("en-uk").name}</h2>
              <p>{translation.subcategory}</p>
              <p>{translation.subcategory_desc}</p>
              {/* Display other data properties for each translation */}
            </div>
          );
        })}
    </div>
  );
};

export default Home;
8ljdwjyq

8ljdwjyq1#

好吧,我有时间检查一下这个问题。你的问题是当你试图在return调用中访问你的数据时,你试图MapdiseaseData.translations的键,然后你引用了getTranslation方法,但是这个方法不跟踪你的状态(diseaseData)。之后,当迭代翻译时,您使用的是{translation("en-uk").name},大致翻译为“以"en-uk"作为参数调用translation方法,并返回您得到的结果的name字段。
以下是如何解决此问题:

const Home = () => {
  const [diseaseData, setDiseaseData] = useState(null);

  const fetchData = useCallback(async () => {
    fetch("http://127.0.0.1:8000/api/disease/")
      .then((result) => result.json())
      .then((result) => { setDiseaseData(result); })
      .catch((error) => console.error(error));
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]); // You missed a dependency here
  
  const getTranslation = useCallback((langCode) => { 
    return diseaseData?.translations?.[langCode] || null;
  }, [diseaseData?.translations]); // This dependency array ensures the `getTranslation` method keeps track of the state.

  return (
    <div>
      {Object.keys(diseaseData?.translations ?? {})?.map((langCode) => {
        const translation = getTranslation(langCode);
        if (!translation) {
          return null;
        }
        return (
          <div key={langCode}>
            <h2>{translation.name}</h2>
            <p>{translation.subcategory}</p>
            // ...
          </div>
        )
      })}
    </div>
  )
};

顺便说一句,稍后可能会出现一些性能问题(特别是在返回的map中引用getTranslation的方式,但我没有触及这一点,因为您可能刚刚开始您的项目,我不想用太多的信息淹没您,所以我只提供了您面临的问题的解决方案。如果你感兴趣,请随时询问!

相关问题